我的 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;
}
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,它会打印“GrandParent:printMe”。我的目标是打印“Child: printMe!”。重写 printMe 是否有问题?
你试图做的事情是不可能的。在 的构造函数时GrandParent,对象中唯一Child被构造和初始化的部分是该GrandParent部分 - 包括 vtable。也就是说,当您调用 时printMe(),条目将是GrandParents。只有在Child构造之后, 的 vtable 条目printMe()才会更新为指向Child::printMe。
请注意,C++ 像这样工作是件好事。如果Child::printMe 是被调用的那个,那么您将在尚未构造的对象上调用成员函数。这样做不会有什么好处。
| 归档时间: |
|
| 查看次数: |
3703 次 |
| 最近记录: |