我在我的C ++代码上遇到了麻烦..
class GrandParent {
public:
GrandParent()
{
printMe();
}
virtual void printMe()
{
std::cout << "GrandParent: printme" << std::endl;
}
}
class Parent : public GrandParent {
public:
Parent(){}
virtual void printMe()
{
std::cout << "Parent: printMe!" << std::endl;
}
}
class Child : public Parent {
public:
Child(){}
void printMe()
{
std::cout << "Child: printMe!" << std::endl;
}
}
int main()
{
Child *p = new Child();
delete p;
}
当我运行此代码时,它将打印“ GrandParent:printMe”。我的目标是打印“ Child:printMe!”。覆盖printMe有什么问题吗?
您尝试做的事是不可能的。在GrandParent
的构造函数时,Child
已构造和初始化的对象的唯一部分是该GrandParent
部分-包括vtable。也就是说,当您调用时printMe()
,条目将为GrandParent
。只有在Child
构造之后,的vtable条目printMe()
才会更新为指向Child::printMe
。
请注意,C ++可以像这样工作。如果Child::printMe
曾经被调用过,那么您将在一个尚未构造的对象上调用成员函数。没有任何好处。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句