c++ - 尝试从 C++ 中的构造函数继承类时出错

标签 c++ inheritance constructor

我的代码有问题。学生类将字符串 studName 和 studRegNum 定义为 protected 数据成员。我创建了一个构造函数,它具有用于初始化数据成员的参数。类 studentAthlete 继承自 student 并有一个私有(private)数据成员 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();

}

最佳答案

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

学生运动员。没有构造函数。因此,当您创建一个 studentAthlete 时,它无法构造其基类。有两个简单的解决方案:

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

关于c++ - 尝试从 C++ 中的构造函数继承类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55691573/

相关文章:

c++ - 为什么类内初始化器不能使用 ( )

Java:如何查找是否从基类重写了一个方法?

c++ - 如果 voidPtr 是空指针或指向从 Base 继承的对象,dynamic_cast<Derived*>(static_cast<Base*>(voidPtr)) 会出错吗?

python - 继承 : Base class method which returns an instance of itself

javascript - 构造函数返回值不是 "[Object object]"

c++ - 声明引用在类中有效,但在主函数中无效

c++ - 重构 fopen_s

c++ - for循环中的赋值语句

Java将变量从父类(super class)传递到子类

Java:创建其构造函数可能引发异常的静态类成员