[英]How to access derived class member function using Base class function?
我正在尝试设计一个停车系统(低级设计)
有些类的行为是这样的。
class Vehicle
{
public:
int entryTime;
int exitTime;
virtual void leaveParking(Vehicle*);
virtual int getChargePerHr();
//virtual void getChargePerHr() = 0;
Vehicle() {}
};
class Car : public Vehicle
{
private :
int chargePerHr = 30;
public:
void leaveParking(Vehicle*);
int getChargePerHr();
Car(){}
};
class Bike : public Vehicle
{
private :
int chargePerHr = 10;
public:
void leaveParking(Vehicle*);
int getChargePerHr();
Bike(){}
}
void Vehicle ::leaveParking(Vehicle* v)
{
int pay = v-> // Here expecting Car class member function getChargePerHr() should come
//so that I can access private member chargePerHr of car class.
// But I am not able to access the Car class member function here.
}
int main()
{
Car c1; // assume Car c1 has already parked.
Vehicle v;
Vehicle* vptr = new Vehicle();
vptr = new Car();
c1.leaveParking(vptr); // Car c1 wants to leave the parking place
}
我想使用基础 class 车辆成员 function 访问汽车 class 的 getChargePerHr()。
我尝试使用纯虚拟 function 但仍然无法成功。
谁能帮帮我?
问题
这里:
void Vehicle::leaveParking(Vehicle* v)
{
...
}
您无法访问Car::getChargePerHr()
因为v
是Vehicle
而不是Car
。 显然,您正在尝试实现多态性,因为您似乎希望Vehicle
的派生类在它们离开停车场时执行相同的操作。
解决方案
Vehicle::getChargePerHr()
声明为纯虚拟(如果需要默认实现,则为虚拟)getChargePerHr()
的实现Vehicle
中定义的方法实现Vehicle::leaveParking()
在运行时,虚拟表将解析覆盖并调用正确的派生实现。
其他问题
您从Vehicle
继承而没有声明其析构函数为虚拟的。 这意味着如果任何子类需要执行清理,它们的析构函数将不会被调用。
Bike
class 声明后缺少分号。
如果每辆车在离开停车场时都做同样的事情,那么让Vehicle
leaveParking()
成为虚拟是没有意义的——如果你想让一个成员 function 能够被子类覆盖,你就可以让它成为虚拟成员。
Vehicle::leaveParking()
可能不应该将另一辆车作为参数。 function 作用于车辆本身,而不是作用于其他车辆。
如果您的构造函数为空,最好将其排除在 class 声明之外,因为它会使可能阅读您代码的其他人感到困惑。
还有更多问题。 我建议你接受 aalimian 的建议来阅读 C/C++。 您的代码显示了许多误解。
代码
将所有内容放在一起,这是一个示例:
class Vehicle
{
public:
int entryTime;
int exitTime;
virtual ~Vehicle() = default;
void leaveParking();
virtual int getChargePerHr() = 0;
};
void Vehicle::leaveParking()
{
// This will call a derived class's implementation
int pay = getChargePerHr();
// Do more vehicle stuff
}
class Car : public Vehicle
{
private:
int chargePerHr = 30;
public:
int getChargePerHr() override;
};
int Car::getChargePerHr()
{
return chargePerHr;
}
class Bike : public Vehicle
{
private:
int chargePerHr = 10;
public:
int getChargePerHr() override;
};
int Bike::getChargePerHr()
{
return chargePerHr;
}
您可以在这里看到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.