1、構造函數
類的一種特殊的成員函數,它會在每次創建類的對象時執行。構造函數的名稱與類的名稱完全相同,並不會返回任何類型,也不會返回void(無類型)。
作用:初始化對象的數據成員。
①默認構造函數
class Shape { public: Shape();//Shape構造函數 void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } int getWidth() { return width; } int getHeight() { return height; } private: int width; int height; }; //定義Shape構造函數 Shape::Shape(void) { cout << "Shape已經被創建" << endl; }
②帶參數的構造函數
構造函數帶參數,這樣在創建對象時就會給對象創建初始值。
class Shape { public: Shape(int w,int h);//帶參數的Shape構造函數 void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } int getWidth() { return width; } int getHeight() { return height; } private: int width; int height; }; //定義帶參數的Shape構造函數 Shape::Shape(int w,int h) { cout << "Shape已經被創建" << endl; cout << "寬為" << w << endl; cout << "高為" << h << endl; }
2、拷貝構造函數
拷貝構造函數是一種特殊的構造函數,函數的名稱和類的名稱一致。它的唯一的一個參數是本類型的一個引用變量。該參數是const類型,不可變的。
相同類型的類對象是通過拷貝構造函數來完成整個復制過程的。
當類的對象需要拷貝時,拷貝構造函數將會被調用。以下情況都會調用到拷貝構造函數:
①一個對象需要通過另外一個對象進行初始化。案例:https://www.cnblogs.com/alantu2018/p/8459250.html
②一個對象以值傳遞的方式傳入函數體。案例:https://www.cnblogs.com/alantu2018/p/8459250.html
③一個對象以值傳遞的方式從函數返回。
class Shape { public: //帶參數的Shape構造函數 Shape(int w, int h) { width = w; height = h; cout << "Shape已經被創建" << endl; } //拷貝構造函數 Shape(const Shape &s) { width = s.width; height = s.height; cout << "調用拷貝構造函數" << endl; } int getWidth() { return width; } int getHeight() { return height; } private: int width; int height; };
3、析構函數
析構函數的名稱與類的名稱相同,在前面加~作為前綴。它不會返回任何值,也不能帶任何參數。它在每次刪除對象時執行,有助於釋放資源。
4、虛函數
在某基類中聲明為virtual並在一個或多個派生類中被重新定義的成員函數。
作用:實現多態性,通過指向派生類的基類指針或引用,訪問派生類中同名覆蓋成員函數。