还有另一种方法可以从基本指针对象调用派生类方法而不进行转换?
class Base
{
};
class Derived : public Base
{
public:
void set() {printf("bbbbbbbbbbbb"); }
};
int main()
{
Base* pbBase;
pbBase = new Derived();
//pbBase->set(); // Compilation error.
(Derived*)pbBase->set(); // Working.
}
最佳答案
您可以在virtual
中覆盖的Base
中添加Derived
方法。
注意,您也应该将析构函数设为virtual
,否则当通过基类指针对对象进行delete
时,派生类的析构函数将不会被调用。
#include <iostream>
class Base
{
public:
virtual ~Base() = default;
virtual void set() = 0; // = 0 makes it pure virtual
};
class Derived : public Base
{
public:
void set() override { std::cout << "bbbbbbbbbbbb\n"; }
};
int main()
{
Base* pbBase;
pbBase = new Derived();
pbBase->set();
delete pbBase;
}
关于c++ - 从基类实例调用派生类方法而无需强制转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62374290/