使用动态指针就是为了表达一种动态调用的性质即当前指针指向哪个对象,就调用那个对象对应类的成员函数。那要怎么来解决的,这时虚函数就体现出了它的作用:
#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;
}
#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,那么执行结果: