关于构造函数中的多态性的一个小问题

编程入门 行业动态 更新时间:2024-10-25 12:27:06
本文介绍了关于构造函数中的多态性的一个小问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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"); }

推荐答案

Quote:

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?[^]

Quote:

pA- > msg(); //将消息(B);

pA->msg();//will Message("B");

这是通常的polimorphic行为。

This is the usual polimorphic behaviour.

编辑:Richard MacCutchan提出了写作的好主意关于这个问题的提示/技巧。我刚刚用一个关于这个问题的示例代码进行了一个小讨论:永远不要在C ++ / C#/ Java中从类的构造函数或析构函数中调用虚方法! [ ^ ] 我懒得写这里是答案,因为我已经回答了几次这个问题。原因如下:永远不要直接或间接地从(基类)构造函数中调用虚方法。请阅读我的帖子: www.codeproject/Messages/4619258/Re-Serial-Port-OK-in-class-constructor-but-not-out.aspx [ ^ ] www.codeproject/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: www.codeproject/Messages/4619258/Re-Serial-Port-OK-in-class-constructor-but-not-out.aspx[^] www.codeproject/Messages/4619708/Re-Serial-Port-OK-in-class-constructor-but-not-out.aspx[^]

更多推荐

关于构造函数中的多态性的一个小问题

本文发布于:2023-08-04 06:02:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293608.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多态性   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!