c-从基类指针调用派生类非虚拟成员函数
作者:互联网
我们知道,可以通过C中的基类指针访问派生类成员函数,前提是这些成员函数必须是虚拟的.有没有一种方法可以从基类指针访问派生的类成员函数,而这些成员函数不是虚拟的也不是纯虚拟的.
即我想调用仅在派生类&中存在的派生类成员函数.通过基类指针不在基类中.我将如何实现?
例如,如果我设计了工厂设计模式,
class Vehicle {
public:
virtual void printVehicle() = 0;
static Vehicle* Create(VehicleType type);
};
class TwoWheeler : public Vehicle {
public:
void printVehicle() {
cout << "I am two wheeler" << endl;
}
void Some2WheelerONLYSpecificOPeration()
{
}
};
class ThreeWheeler : public Vehicle {
public:
void printVehicle() {
cout << "I am three wheeler" << endl;
}
void Some3WheelerONLYSpecificOPeration()
{
}
};
class FourWheeler : public Vehicle {
public:
void printVehicle() {
cout << "I am four wheeler" << endl;
}
void Some4WheelerONLYSpecificOPeration()
{
}
};
// Factory method to create objects of different types.
// Change is required only in this function to create a new object type
Vehicle* Vehicle::Create(VehicleType type) {
if (type == VT_TwoWheeler)
return new TwoWheeler();
else if (type == VT_ThreeWheeler)
return new ThreeWheeler();
else if (type == VT_FourWheeler)
return new FourWheeler();
else return NULL;
}
int main()
{
Vehicle* basePtr = Vehicle::Create(VT_TwoWheeler);
basePtr->Some2WheelerONLYSpecificOPeration(); //HOW TO ACHIEVE THIS CALL
basePtr = Vehicle::Create(VT_ThreeWheeler);
basePtr->Some3WheelerONLYSpecificOPeration(); //HOW TO ACHIEVE THIS CALL
basePtr = Vehicle::Create(VT_FourWheeler);
basePtr->Some4WheelerONLYSpecificOPeration(); // //HOW TO ACHIEVE THIS CALL
}
解决方法:
I want to call derived class member functions which are present only in derived class & not in base class through base class pointer. How would I achieve this ?
您不能使用指向基类的指针来调用派生类的非虚拟成员函数.
您将需要一个指向派生类的指针.最简单的方法是使用dynamic_cast获取指向派生类的指针,检查强制转换是否成功,然后使用派生类指针调用派生类成员函数.
更好的方法是在基类中提供虚拟成员函数,并在派生类中实现它.
标签:c,c11,inheritance,virtual,virtual-functions 来源: https://codeday.me/bug/20191009/1881442.html