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; }