【发布时间】: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