gpt4 book ai didi

c++ - 从基类指针调用派生类非虚成员函数

转载 作者:行者123 更新时间:2023-11-30 03:30:14 24 4
gpt4 key购买 nike

我们知道,派生类成员函数可以通过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++ - 从基类指针调用派生类非虚成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45150695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com