从具有多态性的类中检索数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从具有多态性的类中检索数据相关的知识,希望对你有一定的参考价值。
我正在尝试创建一个酒店房间控制系统,我正在尝试实施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,但是我得到一个很大的负数。也许是记忆位置?
不知道哪里出错了,感谢任何帮助!
答案
替换this
或更改参数名称(如@ KarstenKoop的回答)是使用成员初始化列表(如@melpomene提到的),如下所示:
HotelRoom(int room_number, double cost_per_night)
: room_number(room_number), cost_per_night(cost_per_night)
{
}
顺便说一句,定义函数后不需要;
。
另一答案
在你的构造函数中
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
相同。
以上是关于从具有多态性的类中检索数据的主要内容,如果未能解决你的问题,请参考以下文章