【问题标题】:Error when trying to inherit from class with constructor in C++尝试使用 C++ 中的构造函数从类继承时出错
【发布时间】:2019-04-15 14:37:20
【问题描述】:

我的代码有问题。学生类将字符串 studName 和 studRegNum 定义为受保护的数据成员。我创建了一个构造函数,它具有初始化数据成员的参数。类 studentAthlete 继承自 student 并且有一个私有数据成员 sport,它描述了学生所从事的运动。两个类都有一个成员函数 identify() 输出学生信息。

当我运行代码时,我收到错误消息“没有匹配函数调用'student::student()'”

请帮忙。我是 C++ 新手 以下是我的代码:

#include <iostream>
using namespace std;

class student
{
protected:
    string studName;
    string studRegNum;
public:
    //Constructor prototype
    student(string name, string regNo);
    void identify();
};
//Constructor for student class
student::student(string name, string regNo):
studName(name), studRegNum(regNo)
{

}
class studentAthlete : public student
{
private:
    string member_sport;
    string get_member_sport(string member_Sport);
public:
    void identify();
    studentAthlete(string Sport);
};
studentAthlete::studentAthlete(string Sport):
member_sport(Sport)
{
}
string studentAthlete::get_member_sport(string member_Sport)
{
    member_Sport=member_sport;
    return member_sport;
}

void studentAthlete::identify()
{
    cout<<"Student Name: "<<studName<<endl;
    cout<<"Student Registration Number: "<<studRegNum<<endl;
    cout<<"Student sport: "<<member_sport<<endl;
}


int main()
{
    string studentName, registrationNO, studentSport;//Variables that will hold student information
    cout<<"Enter Student name: "<<endl;
    cin>>studentName;
    cout<<"Enter Registration number: "<<endl;
    cin>>registrationNO;
    cout<<"Enter Student Sport: "<<endl;
    cin>>studentSport;
    student st(studentName,registrationNO);
    studentAthlete sa(studentSport);
    cout<<"Student Details: ";sa.identify();

}

【问题讨论】:

  • 你为什么不为studentAthlete 写一个构造函数?
  • studentAthlete 类对象与studentAthlete sa; 的实例化尝试调用其基类的不存在的默认构造函数。
  • 学生没有默认构造函数
  • @vik_78 我对 C++ 很陌生。如何在学生中创建默认构造函数?
  • 你没有写studentAthlete构造函数->默认生成->它调用基类的默认构造函数->你在student中实现了自己的构造函数==没有更多的“默认, 没有参数”的构造函数存在 -> 错误

标签: c++ inheritance constructor


【解决方案1】:

您在student 中定义了一个构造函数,它接受两个参数。它没有默认(“无参数”)构造函数,因为您定义了一个。

studentAthlete。没有构造函数。所以当你创建一个studentAthlete 时,它不能构造它的基类。有两种简单的解决方案:

  • student 中创建一个无参数构造函数
  • studentAthelete 中创建一个构造函数,该构造函数调用您在student 中定义的构造函数

【讨论】:

  • 要做第2点,你需要知道Member Initializer List
  • @CiscoIPPhone 即使在使用 studentAthelete 的构造函数编辑代码后,我仍然遇到同样的错误
  • 你能发布你更新的代码@KalisploitTutorials 吗?如果您创建了 studentAthelete,则必须确保它会在 student 中调用构造函数 - 请参阅 user4581301 的评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多