用C++1)编写一个名为Person的类,该类包含name和age属性以及一个show( )方法用于打印姓名和年龄信息; (2)编写一个名为Teacher的类,该类公有继承自Person类,并且增加major属性用来表示教师的专业,增加sleep( )方法打印教师的睡觉时间; (3)编写一个主函数,在该函数中分别实例化一个Person对象和Teacher对象,用Person对象调用show( )方法,用Teacher对象调用show( )方法和sleep( ),观察运行结果。
时间: 2024-03-12 08:49:58 浏览: 51
C++类的教学
好的,下面是 C++ 的代码实现:
```c++
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
void show() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
class Teacher : public Person {
public:
string major;
void sleep() {
cout << "Teacher's sleep time is 8 hours." << endl;
}
};
int main() {
Person p;
p.name = "Jack";
p.age = 30;
p.show();
Teacher t;
t.name = "Tom";
t.age = 40;
t.major = "Math";
t.show();
t.sleep();
return 0;
}
```
运行结果如下:
```
Name: Jack, Age: 30
Name: Tom, Age: 40
Teacher's sleep time is 8 hours.
```
阅读全文