编写一个主函数,在该函数中分别实例化一个Person对象和Teacher对象,用Person对象调用show( )方法,用Teacher对象调用show( )方法和sleep( ),观察运行结果。 c++代码
时间: 2023-12-14 09:35:56 浏览: 35
```cpp
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
Person(string n, int a) : name(n), age(a) {}
void show() {
cout << "My name is " << name << ", I'm " << age << " years old." << endl;
}
private:
string name;
int age;
};
class Teacher : public Person {
public:
Teacher(string n, int a, string t) : Person(n, a), title(t) {}
void show() {
cout << "I'm a teacher, my name is " << getName() << ", I'm " << getAge() << " years old, and my title is " << title << "." << endl;
}
void sleep() {
cout << "I'm sleeping." << endl;
}
private:
string title;
};
int main() {
Person p("Tom", 20);
Teacher t("Mary", 30, "professor");
p.show();
t.show();
t.sleep();
return 0;
}
```
输出结果为:
```
My name is Tom, I'm 20 years old.
I'm a teacher, my name is Mary, I'm 30 years old, and my title is professor.
I'm sleeping.
```
阅读全文