C++多态基础性练习
2017-01-13 10:30:00         来源：Steve_Abelieve

C++多态基础性练习：动态多态、虚函数，要求：1.定义Shape类，成员函数：calcArea(),构造函数、析构函数
2.定义Rec类，成员函数：calArea(),构造函数、析构函数。

3.定义Circle类，成员函数：calArea(),构造函数、析构函数

1.不加同名函数前不加virtual关键字
Shape*shape1 = new Rect(3,5);
Shape *shape2 = new Circle(5);
shape1->calcArea();
shape2->calcArea();

2.加上virtauala关键字后，调用子类计算函数

//头文件

```#include
#include
#include

using namespace std;

class Shape
{
public:
Shape();
~Shape();
double calcArea();

};

class Circle:public Shape
{
public:
Circle(double r);
~Circle();
double calcArea();
protected:
double m_dR;

};
class Rect :public Shape
{
public:
Rect(double width,double height);
~Rect();
double calcArea();
protected:
double m_dWidth;
double m_dHeight;

};```

//定义部分：

```#include"Mult.h"

Shape::Shape()
{
cout << "Shape()" << endl;
}
Shape::~Shape()
{

cout << "~Shape()" << endl;
}
double Shape::calcArea()
{

cout << " Shape->calcArea()" << endl;
return 0;
}

Circle::Circle(double r)
{
m_dR = r;
cout << "Circle()" << endl;

}
Circle::~Circle()
{
cout << "~Circle()" << endl;

}
double Circle::calcArea()
{
cout << "Circle->calcArea()" << endl;
return 3.14*m_dR*m_dR;
}

Rect::Rect(double width, double height)
{
m_dWidth = width;
m_dHeight = height;
cout << "Rect()" << endl;
}
Rect::~Rect()
{
cout << "~Rect()" << endl;
}
double Rect::calcArea()
{
cout << "Rect->calcArea()" << endl;
return m_dWidth*m_dHeight;
}
```

//测试部分

```#include"Mult.h"
int main(void)
{
Shape*shape1 = new Rect(3,5);
Shape *shape2 = new Circle(5);
shape1->calcArea();
shape2->calcArea();

delete shape1;
shape1 = NULL;
delete shape2;
shape2 = NULL;

system("pause");
return 0;
}```