虚函数学习

#include "stdafx.h"
#include<iostream>
using namespace std;

class BASE0 //抽象类 不能实例化 不能定义对象但可以
	       //定义它的引用和指针(可以指向派生类的对象)
{
public:
		virtual void test()const =0;//纯虚函数
};

class	BASE1
{
public:
	virtual ~BASE1();//定义虚析构函数则其派生类的析构函数也是虚析构。
	virtual void display()const;//虚函数,定义为常对象因其不会改变对象状态。
};


BASE1::~BASE1()
{
	cout<<"base1 destory"<<endl;
}
void BASE1::display()const
{
	cout<<"base1 display"<<endl;
}

class BASE2:public BASE1,public BASE0
{
public:
	virtual ~BASE2();
	virtual void display()const;
	void test() const ;//覆盖基类纯虚函数 没有使用virtual 定义因为他和基类的test()
	                   //具有相同返回值、参数、名称
};

BASE2::~BASE2()
{
	cout<<"base2 destory"<<endl;
}
void BASE2::display()const
{
	cout<<"base2 display"<<endl;
}

void BASE2::test()const
{
	cout<<"test base2 :"<<endl;
}
class BASE3:public BASE2
{
public:
	virtual ~BASE3();
	virtual void display() const;
	void test() const;
};

BASE3::~BASE3()
{
	cout<<"base3 destory"<<endl;
}

void BASE3::display()const
{
	cout<<"base3 display"<<endl;
}

void BASE3::test()const
{
	cout<<"BASE3 test"<<endl;
}
void fun(BASE1 *ptr)
{
	ptr->display();
}

void virtualTest(BASE0 *ptr1)
{
	ptr1->test();
}
int _tmain(int argc, _TCHAR* argv[])
{
	BASE1  ba1;
	BASE2  ba2;
	BASE3  ba3;
	fun(&ba1);
	fun(&ba2);
	virtualTest(&ba2);//基类指针指向了派生类的对象
	fun(&ba3);
	return 0;
}

虚析构补充:

通过基类指针调用对象析构函数若其析构函数不是虚函数则有可能产生不确定结果

#include "stdafx.h"
#include<iostream>
using namespace std;
class BA
{
public:
	//~BA()若这样定义在此例中则不能调用派生类的析构函数
	virtual ~BA()
	{
		cout<<"BA destructor"<<endl;
	}
};

class BB:public BA
{
public:
	BB()
	{
		p= new int(0);
	}
	~BB()
	{
		cout<<"BB destructor"<<endl;
		delete p;
	}
private:
	int *p;
};

void fun(BA * b)
{
	delete b;
}

int _tmain(int argc, _TCHAR* argv[])
{
	BA *b = new BB();
	fun(b);
	return 0;
}
//使用new BB则只调用默认构造函数 ,使用new BB()除了调用默认构造函数外还将基本数据类型和指针类型成员用0赋初值



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值