C++中虚函数机制会导致指针类型的对象无法调用父类方法?

#include “stdafx.h”
#include <boost/signal.hpp>
#include <boost/bind.hpp>
class Parent1
{
public:
 void Method()
 {
  _tprintf(_T(“Parent1::Method()\n”));
 }
};
class Child1: public Parent1
{
public:
 void Method()
 {
  _tprintf(_T(“Child1::Method()\n”));
 }
};
//////////////////////////////////////////////////////////////////////////
// 这里只有这对父子类是真正的虚函数机制
class Parent2
{
public:
 virtual void Method()
 {
  _tprintf(_T(“Parent2::Method()\n”));
 }
};
class Child2: public Parent2
{
public:
 void Method()
 {
  _tprintf(_T(“Child2::Method()\n”));
 }
};
//////////////////////////////////////////////////////////////////////////
class Parent3
{
public:
 void Method()
 {
  _tprintf(_T(“Parent3::Method()\n”));
 }
};
class Child3: public Parent3
{
public:
 virtual void Method()
 {
  _tprintf(_T(“Child3::Method()\n”));
 }
};
int _tmain(int argc, _TCHAR* argv[])
{
 
 Child1 c1;
 Child2 c2;
 Child3 c3;
 boost::signal<void () > SignalTest1, SignalTest2, 
  SignalTest3,SignalTest4,
  SignalTest5, SignalTest6;
 SignalTest1.connect( boost::bind(&Parent1::Method, &c1)  );
 SignalTest1();
 SignalTest2.connect( boost::bind(&Parent2::Method, &c2)  ); // 所以在这里即使指定&Parent2::Method也会调用到Child2::Method
 SignalTest2();
 SignalTest3.connect( boost::bind(&Parent3::Method, &c3)  );
 SignalTest3();
 SignalTest4.connect( boost::bind(&Child1::Method, &c1)  );
 SignalTest4();
 SignalTest5.connect( boost::bind(&Child2::Method, &c2)  );
 SignalTest5();
 SignalTest6.connect( boost::bind(&Child3::Method, &c3)  );
 SignalTest6();
 
 return 0;
}
result:
Parent1::Method()
Child2::Method()
Parent3::Method()
Child1::Method()
Child2::Method()
Child3::Method()

By Lu Jun

80后男,就职于软件行业。习于F*** GFW。人生48%时间陪同电子设备和互联网,美剧迷,高清视频狂热者,游戏菜鸟,长期谷粉,临时果粉,略知摄影。

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.