c++ 构造函数的调用时机和规则

#include <iostream>
#include <string>
using namespace std;
/*
    拷贝构造函数调用
    1.使用一个已经创建完毕的对象来初始化一个对象
    2.值传递的方式给函数传值
    3.值方式返回局部对象
*/
class Person
{
public:
    Person()
    {
        cout << "moren function" << endl;
    }

    Person(int Age)
    {
        cout << "This is calling a argument function!!!" << endl;
        age = Age;
    }
    // 拷贝构造函数
    Person(const Person &p)
    {
        cout << "kaobei function !!!" << endl;
        age = p.age;
    }

    ~Person()
    {
        cout << "This is destructio function!!!" << endl;
    }
    int age;
};

// 1.使用一个已经创建完毕的对象来初始化一个新的对象
void test()
{
    Person p1(20);
    Person p2(p1);

    cout << "The p2's age is " << p2.age << endl;
}

// 2. 值传递的方式给函数参数传值

// 这里有点难理解的地方是 值传递会拷贝一个临时的副本 相当于Person p = p3;隐式构造右边的p3已经有信息了 将信息拷贝给左边的p 修改了p的属性值不会修改p3的属性值
void work(Person p)
{
    cout << "test1" << endl;
}

void test1()
{
    Person p3; // 这行对应的输出moren function
    work(p3);  // 这行对应的输出kaobei function
}

// 3.值方式返回局部对象
// 局部对象 函数执行后会被释放了person对象
Person dowork()
{
    Person person;
    cout << (int *)&person << endl;
    return person; // 利用person创建新的对象
}

void test03()
{
    Person p = dowork();                       // 这里左边的p式dowork的返回的person创建的新的对象
    cout << "P address:" << (int *)&p << endl; // 这两个地址本来是要不一样的 但是这里是一样的 因为编译器进行了优化
}
int main()
{
    // test();
    // test1();
    test03();
    return 0;
}

```cpp
#include <iostream>
#include <string>
using namespace std;
/*
    构造函数调用机制
    默认条件下 c++编译器至少给一个类添加三个函数
    1.默认构造函数(无参,函数体为空)
    2.默认析构函数(无参,函数体为空)
    3.默认拷贝函数,对属性值进行拷贝, 你不写编译器会总动进行赋值

    构造函数调用规则:
    1.如果用户自己定义了有参构造函数,c++不会提供默认的无参构造,但是会提供默认的拷贝函数
    2.如果用户自己定义了拷贝函数,c++不会提供其他构造函数
*/
class Person
{
public:
    // 无参构造函数
    Person()
    {
        cout << "wucan gouzaohanshu" << endl;
    }
    // 有参构造函数
    Person(int Age)
    {
        age = Age;
        cout << "There is a argument gouzao function!" << endl;
    }
    // 拷贝构造函数
    Person(const Person &p)
    {
        age = p.age;
        cout << "This is kaobei gouzao function!!" << endl;
    }
    // 析构函数
    ~Person()
    {
        cout << "This is destruction function!!!" << endl;
    }

    int age;
};

void test1()
{
    Person p; // 默认无参构造函数
    p.age = 18;

    // 显示拷贝构造函数
    Person p2(p);
    cout << "p2's age is " << p2.age << endl;
}

int main()
{
    test1();
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值