繁体   English   中英

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

[英]Pass created object as argument, from inside that object, C++

我正面临以下问题。 我有以下课程, RoomReservation 对于Reservation类,有一个函数( void Reservation :: rsrvRoomAssignment(Room* r) ),用于将Reservation类的Room* rsrvRoom成员分配给Room对象。 我想从Room对象内部调用此类,但是我不知道如何实现将运行代码的创建对象作为参数正确传递。

该代码描述了上述内容:

保留时间

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;
}

室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还是很陌生,因此上述代码片段可能还会出现一些逻辑错误,因此不要太苛刻:)。

感谢您的任何帮助!

在类方法中时, this指示调用它的对象的实例。 在您的情况下,当房间实例X调用X.roomReservationAdd(r) ,它指向房间实例X 因此,您可以简单地调用r->rsrvRoomAssignment(this);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM