通过代码理解 C++ 继承

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CV2017/article/details/83500700
//C++ 单继承
#include <iostream>

using namespace std;

class Shape
{
public:
	void setWidth(int w)
	{
		width = w;
	}
	void setHeight(int h)
	{
		height = h;
	}
protected:
	int width;
	int height;
};

class Rectangle:public Shape
{
public:
	int getArea()
	{
		return (width * height);
	}
};

int main()
{
	Rectangle rect;
	rect.setWidth(5);
	rect.setHeight(7);
	cout << "Total area:" << rect.getArea() << endl;
	return 0;
}
//C++ 多继承
#include <iostream>

using namespace std;

class Shape
{
public:
	void setWidth(int w)
	{
		width = w;
	}
	void setHeight(int h)
	{
		height = h;
	}
protected:
	int width;
	int height;
};

class PaintCost
{
public:
	int getCost(int area)
	{
		return area * 70;
	}
};

class Rectangle:public Shape,public PaintCost
{
public:
	int getArea()
	{
		return (width * height);
	}
};

int main()
{
	Rectangle rect;
	int area;

	rect.setWidth(5);
	rect.setHeight(7);
	area = rect.getArea();

	cout << "Total area:" << rect.getArea() << endl;
	cout << "Total paint cost:$ " << rect.getCost(area) << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/CV2017/article/details/83500700
今日推荐