C++拷贝构造函数的基本形式

#include <iostream>
#include <string>
using namespace std;

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

   public:
    Person() = default;
    // 当使用常量进行拷贝构造的时候会调用
    Person(const Person& p) { cout << "const copy" << endl; }
    // 当使用非常量进行拷贝构造的时候会调用
    Person(Person& p) { cout << "not const copy" << endl; }
    // 其实可以随便增加额外参数
    Person(Person& p, int a) {}
};

void TestBaseCopy() {
    Person p;
    Person p2 = p;  // 普通变量参数构造函数copy
    const Person p3;
    Person p4 = p3;       // 常量参数构造函数copy
    Person p5(p4, 1000);  // 增加额外参数的拷贝
}
int main(int argc, char const* argv[]) {
    Person p;
    // 1, 2两种形式都是调用非常量参数构造函数
    cout << "1" << endl;
    Person pp1{p};
    cout << "2" << endl;
    Person pp2(p);

    // 3, 4 两种形式,都是先调用非常量参数构造函数,在调用常量参数构造函数
    cout << "3" << endl;
    Person pp3 = Person(p);
    cout << "4" << endl;
    Person pp4 = Person{p};

    // 常量和非常量参数构造函数都存在的时候,会优先调用调用非常量参数构造函数
    // 如果只存在常量参数构造函数,那么就会调用常量参数构造函数
    cout << "5" << endl;
    Person pp5 = {p};

    return 0;
}
原文地址:https://www.cnblogs.com/qiumingcheng/p/15522148.html