关于构造函数中的多态性的一个小问题 [英] a little question about polymorphism in constructor
问题描述
class A{
public:
A(){msg();}
virtual void msg(){AfxMessageBox(_T("A"));}
};
class B: public A{
public:
B():A(){}
private:
virtual void msg(){AfxMessageBox(_T("B"));}
};
void test(){
B b; //will Message("A"); -------why? I think I can get Message("B")!-----
A*pA=&b;
pA->msg();//will Message("B");
}
推荐答案
B b; //将消息(A); - - - -为什么?我想我可以得到消息(B)!-----
B b; //will Message("A"); -------why? I think I can get Message("B")!-----
B
构造函数明确地调用一个
构造函数,因此你得到这样一条消息。
对不起,这是错误的,因为 pasztorpisti 指出。您可以在这里找到正确的信息:
C ++ FAQ:[23.5]当我的基类的构造函数在其对象上调用虚函数时,为什么不调用我的派生类对该虚函数的重写? [ ^ ]
B
constructor explicitely calls the A
constructor, hence you get such a message.
Sorry, that was wrong, as pasztorpisti pointed out. You may find correct info here:
C++ FAQ: [23.5] When my base class's constructor calls a virtual function on its this object, why doesn't my derived class's override of that virtual function get invoked?[^]
pA- > msg(); //将消息(B);
pA->msg();//will Message("B");
这是通常的polimorphic行为。
This is the usual polimorphic behaviour.
编辑:Richard MacCutchan提出了写作的好主意关于这个问题的提示/技巧。我刚刚用一个关于这个问题的示例代码进行了一个小讨论:永远不要在C ++ / C#/ Java中从类的构造函数或析构函数中调用虚方法! [ ^ ]
我懒得写这里是答案,因为我已经回答了几次这个问题。原因如下:永远不要直接或间接地从(基类)构造函数中调用虚方法。请阅读我的帖子:
http://www.codeproject.com/Messages/4619258/Re-Serial-Port-OK-in-class-constructor-but-not-out.aspx [ ^ ]
http://www.codeproject.com/Messages/4619708/Re-Serial-Port-OK-in-class-constructor-but-not-out.aspx [ ^ ]
Richard MacCutchan came up with a good idea of writing a tip/trick about this problem. I've just put together a small discussion with example code about this problem: Never call virtual methods from the constructor or destructor of your classes in C++/C#/Java![^]
I am lazy to write here the answer again as I have already answered this question a few times. The reason in a few words: Never call virtual methods directly or indirectly from (base class) constructors. Please read my posts regarding this:
http://www.codeproject.com/Messages/4619258/Re-Serial-Port-OK-in-class-constructor-but-not-out.aspx[^]
http://www.codeproject.com/Messages/4619708/Re-Serial-Port-OK-in-class-constructor-but-not-out.aspx[^]
这篇关于关于构造函数中的多态性的一个小问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!