虚函数的应用举例

使用动态指针就是为了表达一种动态调用的性质即当前指针指向哪个对象,就调用那个对象对应类的成员函数。那要怎么来解决的,这时虚函数就体现出了它的作用:

#include <iostream>
#include <string>
class Graph
{
protected:
	double x;
	double y;
public:
	Graph(double x,double y);
	void virtual showArea();//定义为虚函数或virtual void showArea()
};
Graph::Graph(double x,double y)
{
	this->x=x;
	this->y=y;
}
void Graph::showArea()
{
	std::cout<<"计算图形面积"<<std::endl;
}
class Rectangle:public Graph
{
public:
	Rectangle(double x,double y):Graph(x,y){};
	virtual void showArea();//定义为虚函数
};
void Rectangle::showArea()
{
	std::cout<<"矩形面积为:"<<x*y<<std::endl;
}
class Triangle:public Graph
{
public:
	Triangle(double d,double h):Graph(d,h){};
	virtual void showArea();//定义为虚函数
};

void Triangle::showArea()
{
	std::cout<<"三角形面积为:"<<x*y*0.5<<std::endl;
}

class Circle:public Graph
{
public:
	Circle(double r):Graph(r,r){};
	virtual void showArea();//定义为虚函数
};

void Circle::showArea()
{
	std::cout<<"圆形面积为:"<<3.14*x*y<<std::endl;
}

int main()
{
	Graph *graph;
	Rectangle rectangle(10,5);
	graph=&rectangle;
	graph->showArea();

	Triangle triangle(5,2.4);
	graph=▵
	graph->showArea();

	Circle circle(2);
	graph=&circle;
	graph->showArea();
	return 0;
}


如果在main()主函数中用new建立一个派生类无名对象和定义一个基类对象指针,并将无名对象的地址赋给基类对象指针时,当我们用delete运算符来撤销无名对象时,系统只执行基类析构函数,而不执行派生类析构函数。比如:

#include <iostream>
#include <string>

class Graph
{
protected:
	double x;
	double y;
public:
	Graph(double x,double y);
	void virtual showArea();//定义为虚函数或virtual void showArea()
	~Graph();
};

Graph::Graph(double x,double y)
{
	this->x=x;
	this->y=y;
}

void Graph::showArea()
{
	std::cout<<"计算图形面积"<<std::endl;
}

Graph::~Graph()
{
	std::cout<<"调用图形类析构函数"<<std::endl;
}

class Rectangle:public Graph
{
public:
	Rectangle(double x,double y):Graph(x,y){};
	virtual void showArea();//定义为虚函数
	~Rectangle();
};

void Rectangle::showArea()
{
	std::cout<<"矩形面积为:"<<x*y<<std::endl;
}

Rectangle::~Rectangle()
{
	std::cout<<"调用矩形类析构函数"<<std::endl;
}

int main()
{
	Graph *graph;
	graph=new Rectangle(10,5);
	graph->showArea();
	delete graph;

	return 0;
}


因为在撤销指针graph所指的派生类对象,在调用析构函数时,采用静态联编,只调用了Graph类的析构函数。如果也想调用派生类Rectangle类的析构函数的话,可将Graph类的析构函数定义为虚析构函数。其定义的一般格式:

  virtual ~类名()

  {

    函数体

  };

虽然派生类的析构函数与基类的析构函数名字不同,但是如果将基类的析构函数定义为虚函数,由该基类派生而来的所有派生类的析构函数都自动成为虚函数。我们把上一示例中的Graph类的析构函数前加上关键字virtual,那么执行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值