面向對象的知識要點

1、面向對象技術的基本概念

對象、類和繼承

2、C++中的空類默認產生哪些類成員函數?

對於一個空類,編譯器默認產生4個成員函數:默認構造函數、析構函數、拷貝構造函數和賦值函數。

3、類和結構結構

類和結構的區別:

class中變量默認是private,struct中變量默認是public。C++中的關鍵字struct是爲了讓C++編譯器兼容以前用C開發的項目。

struct也可以有:構造函數、析構函數、之間也可以繼承等等。

以下代碼用struct實現:

#include<iostream>
using namespace std;

enum BREED {GOLDEN,CAIRN,DANDIE,SHETLAND,DOBERMAN,LAB};

struct Mammal
{
public:
	Mammal()
		:itsAge(2),itsWeight(5)
	{
	}

	~Mammal()
	{
	}

	int GetAge() const
	{
		return itsAge;
	}

	void SetAge(int age)
	{
		itsAge = age;
	}

	int GetWeight() const
	{
		return itsWeight;
	}

	void SetWeight(int weight)
	{
		itsWeight = weight;
	}

	void Speak() const
	{
		cout<<"\nMammal sound !";
	}

	void Sleep() const
	{
		cout<<"\n Shhh.I'm sleeping. ";
	}

protected:
	int itsAge;
	int itsWeight;
};

struct Dog : public Mammal
{
public:
	Dog()
		:itsBreed(GOLDEN)
	{
	}

	~Dog()
	{
	}

	BREED GetBreed() const
	{
		return itsBreed;
	}

	void SetBreed(BREED breed)
	{
		itsBreed = breed;
	}

	void WagTail() const
	{
		cout<<"Tail wagging...\n";
	}

	void BegForFood() const
	{
		cout<<"Begging for food...\n";
	}

private:
	BREED itsBreed;
};

int main()
{
	Dog fido;
	fido.Speak();
	fido.WagTail();
	cout<<"Fido is "<<fido.GetAge()<<" years old \n";

	return 0;
}

4、成員變量

哪一種成員變量可以在同一個類的實例之間共享?

靜態成員變量在一個類的所有實例間共享數據。如果想限制對靜態成員變量的訪問,則必須把他們聲明爲保護型或私有型。不允許用靜態成員變量去存放某一個對象的數據。靜態成員數據是在這個類的所有對象間共享的。

5、靜態成員變量的使用。代碼如下:

#include<iostream>
 using namespace std;

 class Cat
 {
 public:
	 Cat(int age)
		 :itsAge(age)
	 {
		 HowManyCats++;
	 }

	 virtual ~Cat()
	 {
		 HowManyCats--;
	 }

	 virtual int GetAge()
	 {
		 return itsAge;
	 }

	 virtual void SetAge(int age)
	 {
		 itsAge = age;
	 }

	 static int GetHowMany()//靜態成員函數
	 {
		 return HowManyCats;
	 }

 private:
	 int itsAge;
	 static int HowManyCats;//靜態成員變量
 };

 int Cat::HowManyCats = 0;//靜態成員變量的初始化

 void tele();

 int main()
 {
	 const int MaxCats = 5;
	 int i;
	 Cat* CatHouse[MaxCats];//聲明對象數組
	 for(i=0; i<MaxCats; i++)
	 {
		 CatHouse[i] = new Cat(i);//初始化對象數組
		 tele();
	 }

	 for(i=0; i<MaxCats; i++)
	 {
		 delete CatHouse[i];//釋放對象數組空間
		 tele();
	 }

	 return 0;
 }

 void tele()
 {
	 cout<<"There are "<<Cat::GetHowMany()<<" Cats alive!\n";
 }

6、初始化列表

初始化列表的初始化變量順序是根據成員的聲明順序來執行的。示例代碼如下:

#include<iostream>
#include<string>

using namespace std;

class Base
{
private:
//	int m_i;
//	int m_j;
	//如果將聲明順序改變一下,就會得到不同的結果
	int m_j;
	int m_i;
public:
	Base(int i)
		:m_j(i),m_i(m_j)//按聲明的順序初始化,故m_i會被賦予一個機值
	{
	}
	Base()
		:m_j(0),m_i(m_j)
	{
	}
	int get_i()
	{
		return m_i;
	}

	int get_j()
	{
		return m_j;
	}
};

int main()
{
	Base obj(98);
	cout<<obj.get_i()<<endl
		<<obj.get_j()<<endl;

	return 0;
}


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