#include <iostream>
using namespace std;
class Shape
{
public:
virtual double area() const = 0;
};
class Triangle:public Shape//假设是直角三角形
{
public:
Triangle(double w, double h) :bottom(w), height(h) {};
virtual double area() const { return bottom * height / 2; };
private:
double bottom;
double height;
};
class Square :public Shape//正方形
{
public:
Square(double w, double h) :width(w), height(h) {};
virtual double area() const { return width * height; };
private:
double width;
double height;
};
int main()
{
Triangle tri(3, 4);
Square squ(5, 6);
Shape *pt[2] = { &tri,&squ };
double sum_area;
sum_area = pt[0]->area() + pt[1]->area();
cout << sum_area;
return 0;
}
C++多态(简单例子)
最新推荐文章于 2023-07-11 11:57:41 发布