我面临以下问题。我有以下课程Room
和Reservation
。对于Reservation
类,有一个函数(void Reservation :: rsrvRoomAssignment(Room* r)
)将Room* rsrvRoom
类的Reservation
成员分配给Room
对象。我想要从Room对象内部调用这个类,但我不知道如何实现正确传递运行代码的创建对象作为参数。
代码描述了上述内容:
Reservation.h
class Room;
class Reservation {
public:
static int rsrvCode;
string rsrvName;
unsigned int rsrvDate;
unsigned int rsrvNights;
unsigned int rsrvPersons;
Room* rsrvRoom; // Room assigned to reservation.
Reservation();
~Reservation();
void rsrvRoomAssignment(Room*);
};
Reservation.cpp
#include <iostream>
#include "Reservation.h"
using namespace std;
/*
Constructor & Destructor
*/
void Reservation :: rsrvRoomAssignment(Room* r){
rsrvRoom=r;
}
Room.h
#include "Reservation.h"
class Room {
public:
static unsigned int roomNumber;
unsigned int roomCapacity;
Reservation* roomAvailability[30];
double roomPrice;
Room();
~Room();
bool roomReservationAdd(Reservation*);
};
Room.cpp
#include <iostream>
#include <string>
#include "Room.h"
using namespace std;
/*
Constructor & destructor
*/
bool Room::roomReservationAdd(Reservation* r){
/* some statement that returns flase */
r->rsrvRoomAssignment(/* & of created object */); // This is the problem i described.
return 1;
}
我对OOP很新,所以上面的snipsets可能会有更多的逻辑错误,所以不要太苛刻:)。
感谢您提供任何帮助!
答案 0 :(得分:2)
在类方法中,this
表示调用它的对象的实例。在您的情况下,当房间实例X
调用X.roomReservationAdd(r)
时,
这指向房间实例X
。
因此,您只需拨打r->rsrvRoomAssignment(this);