#include<iostream> #include<string> using namespace std; class Student { public: Student(int n,string nam) { num=n; name=nam; } void display() { cout<<"num:"<<num<<endl; cout<<"name:"<<name<<endl; } protected: int num; string name; }; class Student1:public Student { public: Student1(int n,string name,int a):Student(n,nam) { age=a; } void show() { display(); cout<<"age:"<<age<<endl; } private: int age; }; class Student2:public Student1 { public: Student2(int n,string name,int a,int s):Student1(n,nam,a) { sex=s; } void show_all() { show(); cout<<"score:"<<score<<endl; } private: int score; }; int main() { Student2 stud(10010,"zaiweitao",17,89); stud.show_all(); return 0; }哪里错了?
时间: 2023-12-03 15:42:50 浏览: 56
您在派生类 `Student1` 的构造函数中将 `nam` 作为参数传递,但 `nam` 并没有定义,应该改为 `name`,即:
```
Student1(int n, string name, int a) : Student(n, name) {
age = a;
}
```
同样,在派生类 `Student2` 的构造函数中,应该将参数 `name` 改为 `nam` 或 `name`,并且要在构造函数中初始化 `score`,否则会有编译错误。改正后的代码如下:
```
class Student1 : public Student {
public:
Student1(int n, string name, int a) : Student(n, name) {
age = a;
}
void show() {
display();
cout << "age:" << age << endl;
}
private:
int age;
};
class Student2 : public Student1 {
public:
Student2(int n, string name, int a, int s) : Student1(n, name, a) {
score = s;
}
void show_all() {
show();
cout << "score:" << score << endl;
}
private:
int score;
};
int main() {
Student2 stud(10010, "zaiweitao", 17, 89);
stud.show_all();
return 0;
}
```
注意:在使用继承时,每个派生类的构造函数必须调用直接基类的构造函数,以确保直接基类的成员得到初始化。