多态性---构造函数和析构函数中调用虚函数

参考 C++ primer 15.4.5
/*
构造函数和析构函数中的虚函数
*/
#include<iostream>
using namespace std;
class Base
{
public:
	//在构造函数和析构函数中调用虚函数,则运行自身类型定义的版本。原因是初始化顺序:先基类后派生
	Base()
	{
		Print();
	}
	~Base(){
		Print();
	};
	virtual void Print()
	{
		cout<<"Base Print"<<endl;
	}
	void dd()
	{
		Print();
	}
};
class Derive:public Base
{
public:
	Derive()
	{
		Print();
	}
	~Derive(){};
	virtual void Print()
	{
		i = 10;
		cout<<"Derive Print"<<i<<endl;
	}
	void derive_func(){}
	int a;
private:
	int i;
};
int main()
{
	//new Derive(); 创建了一个派生类对象
	//指针强转,是把一个基类指针指向了一个派生类对象
	//所以这个指针可以访问派生类继承基类的部分,自己独有的像成员函数derive_func就不能访问了
	Base *bp = (Base *)new Derive();
	cout<<"1------"<<endl;
	bp->Print();
	cout<<"2------"<<endl;
	bp->dd();
	cout<<"3------"<<endl;
	delete bp;
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/niu91/article/details/50957674