[英]Pass created object as argument, from inside that object, C++
I am facing the following problem. 我正面临以下问题。 I have the following classes,
Room
and Reservation
. 我有以下课程,
Room
和Reservation
。 For Reservation
class there is a function ( void Reservation :: rsrvRoomAssignment(Room* r)
) that assigns the Room* rsrvRoom
member of Reservation
class, to a Room
object. 对于
Reservation
类,有一个函数( void Reservation :: rsrvRoomAssignment(Room* r)
),用于将Reservation
类的Room* rsrvRoom
成员分配给Room
对象。 I want though to call this class from inside the Room object but i have no clue on how to achieve that properly passing as argument the created object that runs the code. 我想从Room对象内部调用此类,但是我不知道如何实现将运行代码的创建对象作为参数正确传递。
The code describes the above: 该代码描述了上述内容:
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 Reservation.cpp
#include <iostream>
#include "Reservation.h"
using namespace std;
/*
Constructor & Destructor
*/
void Reservation :: rsrvRoomAssignment(Room* r){
rsrvRoom=r;
}
Room.h 室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 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;
}
I am pretty new to OOP so there might be some more logical errors on the above snipsets, so don't be harsh :) . 我对OOP还是很陌生,因此上述代码片段可能还会出现一些逻辑错误,因此不要太苛刻:)。
Thanks for any kind of help! 感谢您的任何帮助!
When inside a class method, this
indicates the instance of the object calling it. 在类方法中时,
this
指示调用它的对象的实例。 In your case, when a room instance X
calls X.roomReservationAdd(r)
, this points to the room instance X
. 在您的情况下,当房间实例
X
调用X.roomReservationAdd(r)
,它指向房间实例X
Hence, you can simply call r->rsrvRoomAssignment(this);
因此,您可以简单地调用
r->rsrvRoomAssignment(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.