C++面向对象入门(十一)类成员为对象类型时, 构造函数与析构函数的调用顺序

当类的成员属性是对象类型时, 对象的构造函数调用顺序:
1, 调用成员属性的构造函数
2, 调用类的构造函数
3, 调用类的析构函数
4, 调用成员属性的析构函数

 

#include <iostream>
#include <string>

using namespace std;

/**
 * 当类的成员属性是对象类型时, 对象的构造函数调用顺序:
 * 1, 调用成员属性的构造函数
 * 2, 调用类的构造函数
 * 3, 调用类的析构函数
 * 4, 调用成员属性的析构函数
 */
class Person {
public:
    Person() {
        cout << "Person类构造函数调用" << endl;
    }

    Person(string &name) : name(name) {
        cout << "Person类构造函数Person(string &name)调用" << endl;
    }

    ~Person() {
        cout << "Person类析构函数调用" << endl;
    }

private:
    string name;
};

class Rider {
private:
    Person driver;
    string name;
public:
    Rider() {
        cout << "Rider类构造函数Rider()调用" << endl;
    }

    Rider(string &name, Person &driver) : name(name), driver(driver) {
        cout << "Rider类构造函数Rider(string& name, Person& driver)调用" << endl;
    }

    ~Rider() {
        cout << "Rider类析构函数调用" << endl;
    }
};

void test1(){
    Rider r;
}

int main() {
    test1();
    system("pause");

    return 0;
}

 

posted @ 2020-08-19 13:27  DNoSay  阅读(471)  评论(0)    收藏  举报