用c++实现以下程序,设某用户有n个房间出租,三个月起租,不足三个月按三个月算,请设计相关类和程序实现对合租房租赁的管理
时间: 2024-03-07 17:46:27 浏览: 14
下面是一个简单的实现,包含了一个房间类和一个用户类:
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Room {
private:
int id; // 房间编号
int price; // 房间价格
int months; // 最短租期(月)
bool rented; // 是否已出租
public:
Room(int id, int price, int months) {
this->id = id;
this->price = price;
this->months = months;
this->rented = false;
}
int get_id() {
return id;
}
int get_price() {
return price;
}
int get_months() {
return months;
}
bool is_rented() {
return rented;
}
bool rent() {
if (!rented) {
rented = true;
return true;
} else {
return false;
}
}
};
class User {
private:
string name; // 用户名
vector<Room*> rooms; // 用户租用的房间列表
public:
User(string name) {
this->name = name;
}
bool rent_room(Room* room) {
if (room->is_rented()) {
return false;
}
rooms.push_back(room);
room->rent();
return true;
}
void print_info() {
cout << "User: " << name << endl;
cout << "Rooms: ";
if (rooms.size() == 0) {
cout << "None" << endl;
} else {
for (int i = 0; i < rooms.size(); i++) {
cout << rooms[i]->get_id() << " ";
}
cout << endl;
}
}
};
int main() {
vector<Room*> rooms;
// 假设有三个房间可供出租
rooms.push_back(new Room(1, 1000, 3));
rooms.push_back(new Room(2, 1200, 3));
rooms.push_back(new Room(3, 1500, 3));
User user1("Alice");
user1.rent_room(rooms[0]);
user1.rent_room(rooms[1]);
user1.print_info();
User user2("Bob");
user2.rent_room(rooms[1]);
user2.rent_room(rooms[2]);
user2.print_info();
return 0;
}
```
这个程序中,房间类`Room`包含了房间编号、价格和最短租期等属性,以及`rent()`方法用于出租房间。用户类`User`包含了用户名和租用的房间列表,以及`rent_room()`方法用于租用房间。在`main()`函数中,我们新建了三个房间,并让两个用户租用了其中的部分房间,最后打印出了用户的租房情况。