C ++继承出错 [英] C++ inheritance getting error

查看:50
本文介绍了C ++继承出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在弄清楚这个错误时遇到了一些麻烦.所以我有一个Person类和一个Student子类.

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

Person类具有以下构造函数:

The Person class has the following constructor:

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

Student类具有以下构造函数:

The Student class has the following constructor:

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

但是当我尝试编译Student类时,对于构造函数却出现此错误:

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

在构造函数"Student :: Student(const string& ;, int)"中:

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

错误:没有匹配的函数可以调用'Person :: Person()'

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

我是C ++的新手,所以我不知道为什么会收到此错误,但显然与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.

推荐答案

您正试图调用 Person 的默认构造函数,但它没有一个.无论如何,看起来您想要做的就是调用其单参数构造函数:

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)
{
}

类似地,在 Person 的构造器中使用构造函数初始化列表:

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.

这篇关于C ++继承出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆