c++编程。定义一个房间类(CRoom),要求拥有的私有数据成员:门牌号(m_ id),门(m_pdoor),窗户(m_window)。其中,门是门类(CDoor)定义的对象指针成员,窗户是窗户类(CWindow)定义的对象成员。要求:每个类单独定义在两个文件中(.h 和.cpp),房间类包括:构造函数、析构函数,InstallDoor成员函数能够实现安装门(new CDoor)的功能。要求窗户类的构造函数必须带参数, CDoor类具有宽度,高度及修改宽度高度功能,CWindow类具有宽度,高度及修改宽度高度功能。设计好后测试。
时间: 2024-02-20 14:01:43 浏览: 129
好的,我来回答您的问题。
以下是CRoom类的头文件CRoom.h的代码:
```cpp
#ifndef CROOM_H
#define CROOM_H
#include "CDoor.h"
#include "CWindow.h"
class CRoom
{
public:
CRoom(int id);
~CRoom();
void InstallDoor(int width, int height);
void SetWindow(int width, int height);
private:
int m_id;
CDoor* m_pdoor;
CWindow m_window;
};
#endif // CROOM_H
```
以下是CRoom类的源文件CRoom.cpp的代码:
```cpp
#include "CRoom.h"
CRoom::CRoom(int id)
: m_id(id), m_pdoor(nullptr), m_window(0, 0)
{
}
CRoom::~CRoom()
{
if (m_pdoor)
{
delete m_pdoor;
m_pdoor = nullptr;
}
}
void CRoom::InstallDoor(int width, int height)
{
if (m_pdoor)
{
delete m_pdoor;
m_pdoor = nullptr;
}
m_pdoor = new CDoor(width, height);
}
void CRoom::SetWindow(int width, int height)
{
m_window.SetSize(width, height);
}
```
以下是CDoor类的头文件CDoor.h的代码:
```cpp
#ifndef CDOOR_H
#define CDOOR_H
class CDoor
{
public:
CDoor(int width, int height);
~CDoor();
void SetSize(int width, int height);
private:
int m_width;
int m_height;
};
#endif // CDOOR_H
```
以下是CDoor类的源文件CDoor.cpp的代码:
```cpp
#include "CDoor.h"
CDoor::CDoor(int width, int height)
: m_width(width), m_height(height)
{
}
CDoor::~CDoor()
{
}
void CDoor::SetSize(int width, int height)
{
m_width = width;
m_height = height;
}
```
以下是CWindow类的头文件CWindow.h的代码:
```cpp
#ifndef CWINDOW_H
#define CWINDOW_H
class CWindow
{
public:
CWindow(int width, int height);
~CWindow();
void SetSize(int width, int height);
private:
int m_width;
int m_height;
};
#endif // CWINDOW_H
```
以下是CWindow类的源文件CWindow.cpp的代码:
```cpp
#include "CWindow.h"
CWindow::CWindow(int width, int height)
: m_width(width), m_height(height)
{
}
CWindow::~CWindow()
{
}
void CWindow::SetSize(int width, int height)
{
m_width = width;
m_height = height;
}
```
最后是测试代码:
```cpp
#include <iostream>
#include "CRoom.h"
using namespace std;
int main()
{
CRoom room(101);
room.InstallDoor(80, 200);
room.SetWindow(120, 150);
cout << "Room " << room.GetID() << " door size: " << room.GetDoorWidth() << " x " << room.GetDoorHeight() << endl;
cout << "Room " << room.GetID() << " window size: " << room.GetWindowWidth() << " x " << room.GetWindowHeight() << endl;
return 0;
}
```
这个程序定义了一个CRoom类,其中包含一个门和一个窗户,门和窗户都是单独的类。主函数创建了一个房间对象,安装了一扇门和一个窗户,并输出门和窗户的尺寸。
希望这个程序对您有帮助!
阅读全文