使用多态从类中检索数据

时间:2019-04-08 11:18:18

标签: c++ oop

我试图创建一个酒店房间控制系统,并试图实现OOP以处理不同类型的房间。

这是名为HotelRoom的父类:

class HotelRoom{
public:
    HotelRoom(int room_number, double cost_per_night){
        room_number = room_number;
        cost_per_night = cost_per_night;
    };

    int get_room_number(){
        return room_number;
    };

    void set_room_number(int new_room_number){
        room_number = new_room_number;
    };

    double get_cost_per_night(){
        return cost_per_night;
    };

    void set_cost_per_night(double cost_per_night){
        cost_per_night = cost_per_night;
    };

    Date get_last_checkin(){
        return last_checkin;
    };

    void set_last_checkin(Date date_checked){
        last_checkin = date_checked;
    };

    bool get_booked(){
        return booked;
    };

    void set_get_booked(bool booked){
        booked = booked;
    };

private:
    int room_number;
    double cost_per_night;
    Date last_checkin;
    bool booked = false;
};

这是名为SingleRoom的子类:

class SingleRoom: public HotelRoom{
public:

    SingleRoom(int room_number, double cost_per_night, string bed_size):HotelRoom(room_number, cost_per_night){
        bed_size = bed_size;
    };

    void set_bed_size(string bed_size){
        bed_size = bed_size;
    }

    string get_bed_size(){
        return bed_size;
    };

private:
    string bed_size;
};

这是主要功能:

int main(){

    SingleRoom new_room(123, 43.22, "Large");
    cout<<new_room.get_room_number()<<endl;

}

运行此代码时,我希望打印出房间号123,但是会得到一个很大的负数。也许是内存位置?

不确定它出了什么问题,并感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

this或更改参数名称的替代方法(如@KarstenKoop的答案)是使用成员初始化程序列表(如@melpomene所述),如下所示:

HotelRoom(int room_number, double cost_per_night)
    : room_number(room_number), cost_per_night(cost_per_night)
{
}

顺便说一句,定义函数后不需要;

答案 1 :(得分:1)

在您的构造函数中

HotelRoom(int room_number, double cost_per_night){
    room_number = room_number;
    cost_per_night = cost_per_night;
};

您正在为其分配参数room_number的值。替换为

this->room_number = room_number;

或以其他方式命名您的成员变量。与cost_per_night相同。