C++类对象构造是,如果有其他类对象作为本类成员时,构造时候先构造类对象,在构造自身.
编译器运行到自身构造函数: 成员类(按顺序)->自身构造
析构的函数调用与构造函数调用相反就vans了.
#include<iostream> #include<string> using namespace std; class Phone { private: string m_PName; public: Phone(string pname) { m_PName = pname; cout << "手机构造函数被调用" << endl; } string getname() { return m_PName; } ~Phone() { cout << "手机析构函数被调用" << endl; } }; class watch { public: watch() { cout << "手表构造函数被调用了" << endl; } ~watch() { cout << "手表析构函数被调用了" << endl; } }; class Person { private: string m_Name; Phone m_phone; watch w; public: Person(string name,string pname): m_Name(name), m_phone(pname){ cout << "人构造函数被调用" << endl; } string getname() { return m_Name; } string getpname() { return m_phone.getname(); } ~Person() { cout << "人析构函数被调用" << endl; } }; int main() { Person p("杨强", "小米mix3"); cout << p.getname() << "的手机型号是" << p.getpname() << endl; } //当其他类对象作为本类成员时,构造时候先构造类对象,在构造自身