某同学设计开发一个游戏,游戏中有墙(Wall)和门(Door),他给出了如下的类定义: class Wall { public: Wall():color(0) { cout<<"构造一面墙"<<endl;} void Paint(int newColor) { color = newColor; cout<<"用新颜色粉刷墙"<<endl; } int GetColor() const {return color;} private: int color; }; class Door { public: Door():openOrClose(false) { cout<<"构造一扇门"<<endl;} void Open() { if (!IsOpened( )){ openOrClose = true; cout<<"门被打开了"<<endl; }else{ cout<<"门开着呢!"<<endl; } } void Close() { if ( IsOpened( ) ) { openOrClose = false; cout<<"门被关上了"<<endl; }else{ cout<<"门关着呢!"<<endl; } } bool IsOpened() const { return openOrClose;} private: bool openOrClose; }; 1)请你用多重继承的方式,实现带有一扇门的墙(WallWithDoor)类。功能变更为: a.当用红色粉刷墙时,关闭门。 b.当用绿色粉刷墙时,打开门。 c.当用其它颜色刷墙时,门的状态不变。 2) 用单继承的方法,实现同样功能 3)用水平关联的方式,实现同样功能
时间: 2024-02-06 08:04:41 浏览: 137
Wall Breaker 破壁者 Unity破墙休闲跑酷游戏项目源码C#
1)请你用多重继承的方式,实现带有一扇门的墙(WallWithDoor)类。
```c++
class WallWithDoor : public Wall, public Door {
public:
void Paint(int newColor) {
if (newColor == 1) {
Close();
Wall::Paint(newColor);
} else if (newColor == 2) {
Open();
Wall::Paint(newColor);
} else {
Wall::Paint(newColor);
}
}
};
```
2)用单继承的方法,实现同样功能
```c++
class WallWithDoor : public Wall {
public:
WallWithDoor(): Door(), color(0) {}
void Paint(int newColor) {
if (newColor == 1) {
Door::Close();
color = newColor;
cout << "用新颜色粉刷墙" << endl;
} else if (newColor == 2) {
Door::Open();
color = newColor;
cout << "用新颜色粉刷墙" << endl;
} else {
Wall::Paint(newColor);
}
}
int GetColor() const { return color; }
private:
int color;
};
```
3)用水平关联的方式,实现同样功能
```c++
class WallWithDoor {
public:
WallWithDoor(): wall(), door(), color(0) {}
void Paint(int newColor) {
if (newColor == 1) {
door.Close();
color = newColor;
cout << "用新颜色粉刷墙" << endl;
} else if (newColor == 2) {
door.Open();
color = newColor;
cout << "用新颜色粉刷墙" << endl;
} else {
wall.Paint(newColor);
}
}
int GetColor() const { return color; }
private:
Wall wall;
Door door;
int color;
};
```
阅读全文