C++第5课——多态

#include "pch.h"
#include 
using namespace std;


class Shape {
protected:
	int width, height;
public:
	Shape(int a, int b):width(a),height(b){}          //构造函数初始化列表
	virtual void area() = 0;      //纯虚函数,在基类中定义虚函数。= 0 告诉编译器,函数没有主体
};


class Rectangle : public Shape {
public:
	Rectangle(int a, int b) :Shape(a, b) { }
	void area()
	{
		/*cout << "Rectangle class area :" << endl;*/
		printf("area=%d\n", width * height);
		//return (width * height);
	}
};


class Triangle : public Shape {
public:
	Triangle(int a, int b) :Shape(a, b) { }
	void area()
	{
		/*cout << "Triangle class area :" << endl;
		return (width * height / 2);*/
		printf("area=%d\n", width * height / 2);
	}
};


// 程序的主函数
int main()
{
	Shape *shape;
	Rectangle rec(10, 7);
	Triangle  tri(10, 5);

	shape = &rec;
	shape->area();

	shape = &tri;
	shape->area();

	return 0;
}

 

你可能感兴趣的:(C++)