我的代码有问题。学生类将字符串 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/