1. 程式人生 > >通過程式碼理解 C++ 繼承

通過程式碼理解 C++ 繼承

//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;
}