11.2.4重学C++之【构造函数调用规则】

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;


/*
    4.2 对象的初始化和清理
    4.2.4 构造函数调用规则
        默认情况下创建一个类,C++编译器至少给该类添加3个函数:
            默认构造函数,无参,函数体为空
            默认析构函数,无参,函数体为空
            默认拷贝构造函数,对属性进行值拷贝
        规则:
            若用户定义有参构造函数,则编译器不再提供默认无参构造,但会提供默认拷贝构造
            若用户定义拷贝构造函数,则编译器不再提供其他普通构造函数
*/


class Person{
public:
    Person(){
        cout << "Person 无参默认构造函数" << endl;
    }
    Person(int _age){
        cout << "Person 有参构造函数" << endl;
        age = _age;
    }
    /*
    Person(const Person & p){
        cout << "Person 拷贝构造函数" << endl;
        age = p.age;
    }
    */
    ~Person(){
        cout << "Person 析构函数" << endl;
    }

    int age;
};


void test1(){
    Person p1;
    p1.age = 18;

    Person p2(p1);
    cout << "p2的年龄:" << p2.age << endl;
}
/*
    Person(const Person & p)未注释时打印
        Person 无参默认构造函数
        Person 拷贝构造函数
        p2的年龄:18
        Person 析构函数
        Person 析构函数
    Person(const Person & p)注释时打印
        Person 无参默认构造函数
        p2的年龄:18
        Person 析构函数
        Person 析构函数
    原因分析
        注释后,编译器自动提供默认的拷贝构造函数,对属性进行值拷贝,即执行age = p.age
*/


void test2(){
    Person p1(28);
    Person p2(p1);
    cout << "p2的年龄:" << p2.age << endl;
}


int main(){
    //test1();
    test2();

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HAIFEI666/article/details/114842165