C++构造函数中不能调用虚函数

时间:2024-01-06 22:16:32

在构造函数中调用虚函数,并不会产生多态的效果,就跟普通函数一样。

c++ primer 第四版中497页15.4.5构造函数和析构中的虚函数讲到,如果在构造函数或析构函数中调用虚函数,则运行的是为构造函数或析构函数自身类型定义的版本。另外,必须通过基类类型的引用或指针进行函数调用才会发生多态。

相关帖子:http://bbs.csdn.net/topics/390537893

//示例1
#include <iostream>
using namespace std; class A
{
private:
int m_a;
public:
A(int a): m_a(a) {show();}
virtual ~A() {};
virtual void show() const {cout << "show a: " << m_a << endl;}
virtual void disp() const {cout << "disp a: " << m_a << endl;}
}; class B: public A
{
private:
int m_b;
public:
B(int a, int b): m_b(b), A(a) {}
void show() const {cout << "show b: " << m_b << endl;}
void disp() const {cout << "disp b: " << m_b << endl;}
}; int main()
{
A* pob3 = new B(100, 200);
pob3->disp();
delete pob3;
return 0;
}

  

//示例1运行结果
show a: 100
disp b: 200
请按任意键继续. . .
//示例2
#include <tchar.h>
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "A构造函数";
Test();
}
~A()
{
cout << "A析构函数";
cout << "A::Test()" << endl;
}
virtual void Test()
{
cout << "A::Test()" << endl;
}
}; class B :public A
{
public:
B()
{
cout << "B构造函数";
Test();
}
~B()
{
cout << "B析构函数";
Test();
}
virtual void Test()
{
cout << "B::Test()" << endl;
}
}; int _tmain(int argc, _TCHAR* argv[])
{
A* pA = new B();
cout << "动态调用:";
pA->Test(); delete pA;
return 0;
}
//示例2运行结果
A构造函数A::Test()
B构造函数B::Test()
动态调用:B::Test()
A析构函数A::Test()
请按任意键继续. . .

  

//http://www.cnblogs.com/vcpp123/p/5795421.html

  

//转载请注明出处
//http://www.cnblogs.com/vcpp123/p/5795421.html

关键词:C++,构造函数,虚函数,多态,重载