有问题的代码如下:
#include <iostream>
#include <vector>
using namespace std;
class HotelRoom {
public:
HotelRoom(int bedrooms, int bathrooms)
: bedrooms_(bedrooms), bathrooms_(bathrooms) {}
virtual int get_price() {
return 50*bedrooms_ + 100*bathrooms_;
}
private:
int bedrooms_;
int bathrooms_;
};
class HotelApartment : public HotelRoom {
public:
HotelApartment(int bedrooms, int bathrooms)
: HotelRoom(bedrooms, bathrooms) {}
int get_price() {
return HotelRoom::get_price() + 100;
}
};
我很难理解 HotelApartment 类的构造函数。 定义为:
HotelApartment(int bedrooms, int bathrooms) : HotelRoom(bedrooms, bathrooms) {}
正在创建 HotelRoom 类的实例,但未将其存储在任何引用中。但是,在调用HostelApartment::get_price()
之后,返回的值与在其上创建HostelRoom对象的参数一致。
这是如何工作的?