C++ inheritance getting error

前端 未结 2 1389
不思量自难忘°
不思量自难忘° 2021-01-21 13:12

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:



        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-21 13:38

    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.

提交回复
热议问题