#define _CRT_SECURE_NO_WARNIGS
#include <iostream>
using namespace std;
class Shape {
public:
virtual void show() = 0;
virtual double ShowArea() = 0;
virtual ~Shape() {};
};
class Square :public Shape {
public:
Square(double a) {
this->a = a;
}
//打印出图形的基本属性:
virtual void show() {
cout << "正方形的边长是:" << a << endl;
}
//得到图形的面积
virtual double ShowArea() {
cout << "正方形的面积是:" << endl;
return this->a*this->a;
}
~Square() {
cout << "正方形的析构函数" << endl;
}
private:
double a;//正方形的边长
};
class Circle :public Shape {
public:
Circle(double r) {
this->r = r;
}
//打印出图形的基本属性:
virtual void show() {
cout << "圆的半径是:" << r << endl;
}
//得到图形的面积
virtual double ShowArea() {
cout << "正方形的面积是:" << endl;
return this->r*this->r*3.14;
}
~Circle() {
cout << "圆的析构函数" << endl;
}
private:
double r;//圆的半径
};
int main(void)
{
Shape * array[2] = { 0 };
for (int i = 0; i < 2; i++)
{
if (i==0)
{
double r;
cout << "请输入圆的半径" << endl;
cin >> r;
array[i] = new Circle(r);
}
else
{
double a;
cout << "请输入正方形的边长" << endl;
cin >> a;
array[i] = new Square(a);
}
}
for (int i = 0; i < 2; i++)
{
array[i]->show();
cout << array[i]->ShowArea() << endl;
delete array[i];
}
return 0;
}
程序运行结果如下图: