将创建的对象作为参数从该对象内部传递给C ++

时间:2017-05-20 12:41:53

标签: c++

我面临以下问题。我有以下课程RoomReservation。对于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可能会有更多的逻辑错误,所以不要太苛刻:)。

感谢您提供任何帮助!

1 个答案:

答案 0 :(得分:2)

在类方法中,this表示调用它的对象的实例。在您的情况下,当房间实例X调用X.roomReservationAdd(r)时, 这指向房间实例X。 因此,您只需拨打r->rsrvRoomAssignment(this);

即可