构造一个父类 father,要求包含id和name两个成员变量。构造子类son继承父类father,子类son中包含age成员变量和printinfo()方法(输出id,name和age);在测试类中
时间: 2023-04-30 08:06:11 浏览: 121
构造一个父类 father,要求包含 id 和 name 两个成员变量;构造子类 son 继承父类 father,子类 son 中包含 age 成员变量和 printinfo() 方法(输出 id、name 和 age);在测试类中。
相关问题
定义父类 Father, 有age,name 属性,定义speak(方法 打印 介绍信息。定义2个子类,boy和gril两个子类,分别实现重写speak0方
法,输出自己的介绍信息。
以下是代码示例:
```python
class Father:
def __init__(self, age, name):
self.age = age
self.name = name
def speak(self):
print("Hello, my name is", self.name, "and I am", self.age, "years old.")
class Boy(Father):
def speak(self):
print("Hi, I am a boy. My name is", self.name, "and I am", self.age, "years old.")
class Girl(Father):
def speak(self):
print("Hi, I am a girl. My name is", self.name, "and I am", self.age, "years old.")
# 测试
father = Father(50, "John")
father.speak()
boy = Boy(10, "Tom")
boy.speak()
girl = Girl(8, "Lily")
girl.speak()
```
输出结果如下:
```
Hello, my name is John and I am 50 years old.
Hi, I am a boy. My name is Tom and I am 10 years old.
Hi, I am a girl. My name is Lily and I am 8 years old.
```
设计两个父类Father和Mother,以及一个Boy子类,Boy类从Father和Mother类中继承相应的方法,并覆盖父类的方法。 如Father类中RepairTV方法 Mother类中SingASong方法
好的,以下是实现:
```cpp
#include <iostream>
using namespace std;
class Father {
public:
virtual void RepairTV() {
cout << "Father is repairing TV." << endl;
}
};
class Mother {
public:
virtual void SingASong() {
cout << "Mother is singing a song." << endl;
}
};
class Boy : public Father, public Mother {
public:
void RepairTV() override {
cout << "Boy is repairing TV." << endl;
}
void SingASong() override {
cout << "Boy is singing a song." << endl;
}
};
int main() {
Boy b;
Father* f = &b;
Mother* m = &b;
f->RepairTV();
m->SingASong();
return 0;
}
```
以上代码定义了两个父类 `Father` 和 `Mother`,以及一个子类 `Boy`。`Boy` 类从 `Father` 和 `Mother` 类中继承了 `RepairTV` 和 `SingASong` 两个方法,并覆盖了父类的方法。在 `main()` 函数中,我们创建了一个 `Boy` 对象,并使用指针调用了 `Father` 和 `Mother` 类的方法,用于测试。