C++ //构造函数调用规则 //1.创建一个类,C++编译器会给每个类添加至少3个函数 //默认构造(空实现) //析构函数(空实现) //拷贝函数(值拷贝) //2.如果我们写了有参构造函数 编译器就不会提供默认构造函数 但是会提供拷贝构造函数 //3.如果我们写了拷贝函数 编译器就不再提供 默认 有参 构造函数

//构造函数调用规则


#include <iostream>
using namespace std;

//1.创建一个类,C++编译器会给每个类添加至少3个函数
//默认构造(空实现)
//析构函数(空实现)
//拷贝函数(值拷贝)

//2.如果我们写了有参构造函数 编译器就不会提供默认构造函数 但是会提供拷贝构造函数


//3.如果我们写了拷贝函数  编译器就不再提供 默认 有参 构造函数

class Person
{
public:
    Person()       //默认构造函数
    {
        cout << "Person的默认构造函数调用" << endl;

    }

    Person(int age)
    {
        cout << "Person的有参构造函数" << endl;
        m_Age = age;
    
    }
    Person(const Person &p)
    {
        cout << "Person的拷贝构造函数调用" << endl;
        m_Age = p.m_Age;
    }

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

    int m_Age;



};

void test01()
{

    Person p;
    p.m_Age = 18;

    Person p2(p);

    cout << "P2的年龄为:" << p2.m_Age << endl;
}

void test02()
{
    Person p (18);

    Person p2(p);
    cout << "P2的年龄为:" << p2.m_Age << endl;
}
int main()
{
    //test01();
    test02();

}

 

posted on 2021-08-06 14:39  Bytezero!  阅读(98)  评论(0编辑  收藏  举报