C++ 接口(抽象类)

C++ 接口(抽象类)

class  Shape
{
	public:
		//纯虚函数
		virtual int getArea() = 0;
		void setWidth(int w) 
		{
			width = w;
		}
		void setHeight(int h)
		{
			height = h;
		}
	protected:
		int width,height;
};
//派生类
class Rectangle : public Shape 
{
	public:
		int getArea() 
		{
			return (width * height);
		}
};
//派生类
class Triangle : public Shape 
{
	public:
		int getArea() 
		{
			return (width * height)/2;
		}
};
int main()
{
	Rectangle rec;
	Triangle tri;

	rec.setWidth(3);
	rec.setHeight(4);
	cout << "rec getAre 面积 =" << rec.getArea() << endl;

	tri.setWidth(3);
	tri.setHeight(4);
	cout << "tri getAre 面积 =" << tri.getArea() << endl;


	return 0;
}

版权声明:本文为weixin_40828023原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。