圖形類,面向對象設計

#include<iostream>
using namespace std;
#define PI 3.14159
class Shape
{
public:
	Shape(){}
	~Shape(){}
	virtual void Draw() = 0;
	virtual double Area() = 0;
};

class Rectangle :public Shape
{
public:
	Rectangle() :a(0), b(0){}    //
	Rectangle(int x, int y) :a(x), b(y) {}
	virtual void Draw()
	{
		cout << "Rectangle area:" << Area() << endl;
	}
	virtual double Area()
	{
		return a * b;
	}
private:
	int a;
	int b;
};

class Circle :public Shape
{
public:
	Circle(double x) :r(x) {}
	virtual void Draw()
	{
		cout << "Circle area:" << Area() << endl;
	}
	virtual double Area()
	{
		return PI*r*r;
	}
private:
	double r;
};

class Square :public Rectangle
{
public:
	Square(int length) :a(length) {}
	virtual void Draw()
	{
		cout << "Square area:" << Area() << endl;
	}
	virtual double Area()
	{
		return a*a;
	}
private:
	int a;
};

int main()
{
	Rectangle rect(10, 20);
	Square square(10);
	Circle circle(8);

	Shape *p;
	p = &rect;
	
	p->Draw();
	p = &square;
	
	p->Draw();
	p = &circle;
	
	p->Draw();

    return 0;
}

這段代碼是爲了體會面向對象。基類Shape中的Draw()和Area()都是純虛函數,所以Shape類是抽象類。這兩個函數必須在子類中給出實現。且Shape不能實例化,所以這裏是用一個指針去訪問Draw和Area。
我對Rectangle類中必須給出默認構造方法Rectangle() :a(0), b(0){} .的理解是:
因爲Square類繼承了Rectangle類,在實例化Square的時候要調用基類的構造方法,此時應該調用不帶參數的構造方法。而當Rectangle自己寫了一個帶參數的構造方法的時候,編譯器不會在給Rectangle自動定義一個不帶參數的默認構造方法了。如果不寫這個行,就會出現這樣的錯誤在這裏插入圖片描述

發佈了134 篇原創文章 · 獲贊 25 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章