#include<iostream> using namespace std; class Person{ protected: int age; string name; public: Person(int a,string n):age(a),name(n){} void introduceMe(){ cout<<age<<name;} }; class teacher:public Person{ protected: int gh; public: //teacher(int a,string n,int g):age(a),name(n),gh(g){} void setInfo(int a,string n,int g){ age=a; name=n; gh=g; } void introduceMe(){ Person::introduceMe(); cout<<gh; } }; int main(){ Person p(20,"lisi"); p.introduceMe(); teacher t; t.setInfo(); t.introduceMe(); return 0; }
时间: 2024-03-03 13:49:55 浏览: 24
这段代码存在一些问题,具体来说:
1. 在teacher类中,存在一个未定义的成员变量gh,应该在类中定义或者声明。
2. 在main函数中,应该调用teacher类的setInfo函数来为teacher对象t设置年龄、姓名和gh,而不是直接调用默认构造函数。
3. 在teacher类中,应该使用父类Person的构造函数来初始化age和name,而不是在setInfo函数中手动赋值。
修改后的代码如下:
```C++
#include<iostream>
using namespace std;
class Person {
protected:
int age;
string name;
public:
Person(int a,string n):age(a),name(n){}
void introduceMe(){
cout<<age<<name;
}
};
class teacher:public Person{
protected:
int gh;
public:
teacher(int a, string n, int g):Person(a, n), gh(g){}
void introduceMe(){
Person::introduceMe();
cout<<gh;
}
};
int main(){
Person p(20,"lisi");
p.introduceMe();
teacher t(30, "wangwu", 100);
t.introduceMe();
return 0;
}
```
注意,我并不知道你想问这段代码的哪方面问题,我只是帮你解答了其中可能存在的语法问题。如果你有其他问题,可以继续提问。