C++在自定义类型中定义其他自定义类型的属性初始化过程

#include <iostream>
#include <string>
using namespace std;
class P {
   public:
    int id;
    string name;

   public:
    P() { cout << "wu can p gou zao " << endl; }

    P(int id, string name) {
        cout << "you can p gou zao" << endl;
    }
};

class Person {
   public:
    int id2 = 202;
    int id1 = 201;
    P p;

   public:
    Person() { cout << "person gou zao " << endl; }
    Person(int id2) : p(1, "qiumc") { cout << "person" << endl; }
    Person(int id2, int id1) {}
    Person(const Person& p) { cout << "const copy" << endl; }
};

int main(int argc, char const* argv[]) {

    // 在参数列表中显示调用了自定义类型的属性的构造函数P(int id, string name)
    Person p(100);
    // 对自定义类型的属性,没有进行显示初始化,默认会调用自定义类型属性的的默认构造函数
    Person p2(1, 2);
    return 0;
}
posted @ 2021-11-08 08:48  邱明成  阅读(162)  评论(0编辑  收藏  举报