接口

http://www.runoob.com/cplusplus/cpp-interfaces.html

#include <iostream>
using namespace std;

// 抽象类
class Shape
{
protected:
	double width;
	double height;
public:
	// 纯虚函数,一个类中至少有一个纯虚函数,则这个类就是抽象类,C++中接口是通过抽象类来实现的
	virtual double getArea() = 0;
	void setWidth(double wid)
	{
		width = wid;
	}
	void setHeight(double hei)
	{
		height = hei;
	}
};

// 派生类
class Rectangle : public Shape
{
public:
	double getArea()
	{
		return width * height;
	}
};

// 派生类
class Triangle : public Shape
{
public:
	double getArea()
	{
		return width * height / 2;
	}
};

int main()
{
	Rectangle rect;
	Triangle tri;

	rect.setWidth(1.22);
	rect.setHeight(2.0);
	cout << "Rectangle Area: " << rect.getArea() << endl;

	tri.setWidth(2.22);
	tri.setHeight(3.0);
	cout << "Triangle Area: " << tri.getArea() << endl;

	system("pause");
	return 0;
}

 运行:

 

posted @ 2018-03-01 22:18  半生戎马,共话桑麻、  阅读(125)  评论(0)    收藏  举报
levels of contents