C++ inheritance getting error

﹥>﹥吖頭↗ 提交于 2020-12-26 09:30:30

问题


I'm having a bit of trouble figuring out this error I have. So I have a Person class, and a Student subclass.

The Person class has the following constructor:

Person(const string &name)
        {   this->name = name;
        }

The Student class has the following constructor:

Student::Student(const string &name, int regNo)
{ this->name = name;
  this->regNo = regNo;
}

When I try to compile the Student class though, I get this error for the constructor:

In constructor 'Student::Student(const string&, int)':

error: no matching function for call to 'Person::Person()'

I'm new to C++, so I have no idea why I get this error, but it has something to do with the inheritance of Person obviously.


回答1:


You are attempting to call Person's default constructor, but it doesn't have one. In any case, it looks like what you want to do is call its single parameter constructor:

Student::Student(const string& name, int regNo) : Person(name), regNo(regNo)
{
}

Similarly, use the constructor initialization list in Person's consructor:

Person(const string& name) : name(name) {}

This way, you are initializing your data members to the desired value, instead of default initializing them and then assigning them new values.




回答2:


You need to delegate to the correct ctor from the base class like this:

Student::Student(const string &name, int regNo)
    : Person( name )
{
  this->regNo = regNo;
}

Note that this uses initializer lists, so you could use the more idiomatic

Student::Student(const string &name, int regNo)
    : Person( name ), regNo( regNo )
{
}

and for the Person ctor:

Person(const string &name)
    : name( name )
{
}

The initializer list is used to initialize base classes and the member variables, everything you don't explicitly put in there is default constructed (and in your code, it is later assigned in the ctor's body). Since Person is not default constructible, you must initialize it in the initializer list.



来源:https://stackoverflow.com/questions/20960991/c-inheritance-getting-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!