定义一个马类,再由此派生出白马类,定义构造函数。定义一个白马类的对象,编写主函数测试类的设计是否合理。
时间: 2024-03-26 18:34:22 浏览: 23
好的,以下是一个简单的马类和白马类的实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Horse {
protected:
string name;
int age;
public:
Horse(string n, int a): name(n), age(a) {}
void run() {
cout << name << " is running!" << endl;
}
};
class WhiteHorse : public Horse {
public:
WhiteHorse(string n, int a): Horse(n, a) {}
void showInfo() {
cout << "Name: " << name << ", Age: " << age << ", Color: White" << endl;
}
};
int main() {
WhiteHorse wh("Snow", 5);
wh.showInfo();
wh.run();
return 0;
}
```
在上面的代码中,马类 `Horse` 有两个成员变量 `name` 和 `age`,以及一个 `run` 函数,表示马在奔跑。白马类 `WhiteHorse` 继承自马类,并加入了一个 `showInfo` 函数,用于显示白马的信息。
在主函数中,我们创建了一个白马对象 `wh`,并调用了它的 `showInfo` 和 `run` 函数。输出结果为:
```
Name: Snow, Age: 5, Color: White
Snow is running!
```
可以看到,我们的类设计合理,并且白马对象的信息和行为都符合预期。