C 物件導向高階程式設計筆記02 GeekBand

2021-07-10 09:19:48 字數 2164 閱讀 4776

第二個周 01

這節課主要講了big three(拷貝構造,拷貝賦值,析構函式)。

為什麼需要這幾個特殊函式?這個週要講的是 class with pointer,在類中成員要使用指標,多半要動態分配記憶體,考慮下面幾種物件的建立和賦值場景

string str1("hello");

string str2(str1);

string str3 = str1;

string str4 = new string("hello");

str2和str3,如果不使用拷貝構造和拷貝賦值,則會使用編譯器預設的拷貝和賦值,bit by bit的拷貝。最終的結果是淺拷貝,而我們通常要的是深拷貝。

以string為例,

class string

private:

char* m_data;

};那為什麼要使用析構函式? 因為類中使用了動態記憶體,需要在析構函式中釋放。

相對比,complex類則不需要big three,因為它類中沒有使用指標,也就不存在說的這些問題。

對於拷貝賦值,copy assignment operator

inline 

string& string::operator =(const string& str)

delete m_data;  // 先delete掉自己

m_data = new char[strlen(str.m_data) + 1)];

strcpy(m_data, str.m_data);  // friend

return *this;

}課程還還提到了自我賦值檢測,如果不做的話,一旦拷貝的是自己,不但效率上保證不了,而且會出錯。因為delete掉m_data後,new的時候,長度為0;

第二週/10

擴充套件補充,類模版,函式模版和其他

ø   靜態變數和靜態函式static

靜態函式沒有this pointer,只能去處理靜態變數

呼叫靜態函式的方法:通過物件呼叫(跟普通類一樣);通過類(class name)呼叫。

即:class account

使用:account::set_rate(5.0);

或者account a;

a.  set_rate(7.0); // 這種方法不同於普通物件的地方在於,它也不傳this poiner給引數。

static的使用例子,單例模式

詳見pdf文件。

另外,static變數(包括全域性和區域性的)只初始化一次,

如:void print_static()

正因為上面做了很多過載,所以有輸出不同型別資料的效果。

ø   模板(類模板class template, 和 函式模板function template)

如果不想把型別寫死,可以考慮使用模板。

template //這一行就是告訴編譯器,t還沒有繫結,使用模板

定義了template,使用方法如

complexc1(1, 1,);   //要明確

typename

繫結什麼型別

complexc1(1, 1,);

上面兩行,編譯器沒看到每一行,都會重新用型別替換一次類**。

模板會造成**的膨脹。但膨脹是必須的。

函式模板

template //class 和 typename同樣效果

inline

const t& min(const t& a, constt& b) {

returnb

編譯器會對函式進行實參推導,然後將template的模板函式用實際函式替換乙份**。

例子中,min函式,只負責比大小,而怎麼比則是資料型別的責任。

模板還有更多細節,如特化,偏特化。後面再詳細學習。

ø   namespace

namespace std {    //標準庫namespace

可以在多個檔案,將多個部分的類包括在std的space中。

如何使用namespace,下面有三種用法

using directive  使用命令

usingnamespace std;  //全部開啟std

using declaration

usingstd::cout;   //只開啟cout

不用using,如在函式中,直接使用std::cout << 2;

C 物件導向高階程式設計 筆記

最近重新複習了一下c 物件導向高階程式設計中知識點,學而時習之,不亦說乎。拷貝建構函式,拷貝的是同型別的物件 賦值建構函式 檢測自我賦值 為什麼?有什麼作用?if this str return this 組合繼承 委託示例 委託 繼承 composite pimpl 編譯防火牆 左邊永遠不用編譯,...

物件導向高階程式設計

相同class的各物件互為友元 class complex int func const complex param private double re,im string inline string string const char cstr 0 else inline string strin...

C 物件導向(高階)

1.構造 委託 乙個建構函式可以呼叫另外的建構函式 class aa int i a i,0 a int i,int j 注 避免遞迴呼叫 例 class aa int i a i,0 a int i,int j a 2.不可變物件和類 immutable object and class 不可變物...