有什么方法可以让我完成以下工作,或者有解决办法吗?我一定是遗漏了什么。
class base
{
public:
int someInt;
virtual void someFunction(){}
};
class derived : public base
{
public:
void someFunction(){}
void anotherFunction(){}
};
int main (int argc, char * const argv[]) {
base* aBasePointer = new derived;
aBasePointer->anotherFunction();
delete aBasePointer
return 0;
}
最佳答案
使用 dynamic_cast<>
向下转型指向派生类的指针(不要忘记测试结果)。
例如
if ((derived* p = dynamic_cast<derived*>(aBasePointer)))
{
// p is of type derived.
p->anotherFunction();
}
关于c++ 多态性——使用基指针访问派生函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9688652/