Car類中,包含type對象,這個type對象該怎樣初始化?
試試在Car的構造函數中初始化ios
#include <iostream> #include <stdio.h> using namespace std; class Type { public: int radius; Type() { cout << "Type()" << endl; } ~Type() { cout << "~Type()" << endl; } Type(int radius) { cout << "Type(int radius)" << endl; this->radius = radius; } }; class Car{ public: Type type; Car(int radius) { printf("%p\n", &type); // type對象已經存在,調用的是Type的默認構造函數 // 默認構造函數,沒有對radius進行初始化,所以radius會是一個垃圾值 cout << "type.radius = " << type.radius << endl; type = Type(radius); // 而這纔是,我想要初始化的對象 /* 兩次打印的地址是同樣的,但它們不是一個對象。 只是編譯器作了優化,把上一個type回收了,在一樣的地址建立了一個新的type, 因此你會發現析構函數調用了兩次 */ printf("%p\n", &type); cout << "type.radius = " << type.radius << endl; } }; int main() { Car car(1); return 0; }
初始化列表就是爲了解決重複建立對象的問題函數
下面採用初始化列表的方式建立對象優化
Car(int radius) : type(radius) { // radius爲1,說明初始化成功 cout << "type.radius = " << type.radius << endl; }
類名::構造函數(參數表):成員變量1(參數表), 成員變量2(參數表), ... { ... } // type是成員變量,type(radius)至關於調用Type(radius) Car::Car(int radius) : type(radius) { // ... } // 基礎類型也能夠採用這樣的方式 Car::Car(int radius, int price) : type(radius), price(price) { // ... }
封閉類:包含成員對象的類this
建立:成員對象 -> 封閉類spa
消亡:封閉類 -> 成員對象設計
建立時,成員對象的建立順序,只取決於聲明順序,與初始化列表無關code
#include <iostream> #include <stdio.h> using namespace std; class Tyre { public: Tyre() { cout << "Tyre contructor" << endl; } ~Tyre() { cout << "Tyre destructor" << endl; } }; class Engine { public: Engine() { cout << "Engine contructor" << endl; } ~Engine() { cout << "Engine destructor" << endl; } }; class Car { private: Engine engine; Tyre tyre; public: Car() { cout << "Car contructor" << endl; } ~Car() { cout << "Car destructor" << endl; } }; int main(){ Car car; return 0; }