我面临以下问题。我有以下类(class), Room
和 Reservation
。对于 Reservation
类,有一个函数 (void Reservation::rsrvRoomAssignment(Room* r)
) 分配 Room* rsrvRoom
成员 Reservation
类,到 Room
对象。虽然我想从 Room 对象内部调用此类,但我不知道如何正确地将运行代码的创建对象作为参数传递。
代码描述了上面的内容:
预订.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*);
};
预留.cpp
#include <iostream>
#include "Reservation.h"
using namespace std;
/*
Constructor & Destructor
*/
void Reservation :: rsrvRoomAssignment(Room* r){
rsrvRoom=r;
}
房间.h
#include "Reservation.h"
class Room {
public:
static unsigned int roomNumber;
unsigned int roomCapacity;
Reservation* roomAvailability[30];
double roomPrice;
Room();
~Room();
bool roomReservationAdd(Reservation*);
};
房间.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 的新手,所以上面的片段可能会有更多的逻辑错误,所以不要太苛刻 :)。
感谢您的帮助!
最佳答案
在类方法内部时,this
表示调用它的对象的实例。在您的例子中,当房间实例 X
调用 X.roomReservationAdd(r)
时,
this 指向房间实例 X
。
因此,您可以简单地调用 r->rsrvRoomAssignment(this);
关于c++ - 将创建的对象作为参数从该对象内部传递,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44086001/