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: ▁▁▁(3分) {age=a; } void show( ) {display(); cout<<"age: "<<age<<endl; } private: int age; }; class Student2:public Student1 {public: ▁▁▁(3分) {score=s;} void show_all() {show(); cout<<"score:"<<score<<endl; } private: int score; };
时间: 2024-03-07 16:52:40 浏览: 258
在 class Student1 中,应该定义一个带参数的构造函数,将 age 初始化为给定的值。应该写成:`Student1(int n, string nam, int a): Student(n, nam), age(a) {}`。
在 class Student2 中,应该定义一个带参数的构造函数,将 score 初始化为给定的值。应该写成:`Student2(int n, string nam, int a, int s): Student1(n, nam, a), score(s) {}`。
相关问题
#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; }哪里错了?
您在派生类 `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;
}
```
注意:在使用继承时,每个派生类的构造函数必须调用直接基类的构造函数,以确保直接基类的成员得到初始化。
#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: {age=a; } void show( ) {display(); cout<<"age: "<<age<<endl; } private: int age; }; class Student2:public Student1 {public: {score=s;} void show_all() {show(); cout<<"score:"<<score<<endl; } private: int score; }; int main( ) {Student2 stud(10010,"Li",17,89); stud.show_all( ); return 0; }
这是一段 C++ 代码,定义了三个类:Student、Student1、Student2。其中,Student1 继承自 Student,Student2 继承自 Student1。每个类都有一些成员变量和成员函数,用于描述学生的信息。代码中的 main 函数创建了一个 Student2 类型的对象 stud,并调用了它的成员函数 show_all() 来显示学生的所有信息。
阅读全文