C++对象初始化与重载赋值运算符

C++对象初始化与重载赋值运算符

对象初始化

如下代码:

#include<iostream>
#include<vector>
#include<cstring>
using namespace std;

class A{
public:
    int val;
    char *buffer;
    A(int n){
        val = n;
        buffer = new char[val];
        cout<<"A construct function."<<endl;
    }
    A(const A &a){
        val = a.val;
        buffer = new char[val];
        memcpy(buffer, a.buffer, val);
        cout<<"A copy construct function."<<endl;
    }
    A& operator=(const A &a){
        val = a.val;
        buffer = new char[val];
        memcpy(buffer, a.buffer, val);
        cout<<"A operator function."<<endl;
        return *this;
    }
    ~A(){
        delete buffer;
        cout<<"A destory function."<<endl;
    }
};

A foo(int a, int b){
    int c = a + b;
    return A(c);
}

int main(){
    A a = foo(4, 5);
    cout<<a.val<<endl;
    return 0;
}

请问会不会调用重载的赋值运算符或者构造函数,会调用几次?

执行代码,输出如下:

A construct function.
9
A destory function.

只调用了一次构造函数,且没有调用重载赋值运算符。这说明代码中只是初始化了对象a,调用构造函数的时机在foo()函数中。

下面这两种初始化方式是一样的,都是只调用了一次构造函数:

A a = foo(4, 5);
A a = A(9);
对象赋值
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;

class A{
public:
    int val;
    char *buffer;
    A(int n){
        val = n;
        buffer = new char[val];
        cout<<"A construct function."<<endl;
    }
    A(const A &a){
        val = a.val;
        buffer = new char[val];
        memcpy(buffer, a.buffer, val);
        cout<<"A copy construct function."<<endl;
    }
    A& operator=(const A &a){
        val = a.val;
        buffer = new char[val];
        memcpy(buffer, a.buffer, val);
        cout<<"A operator function."<<endl;
        return *this;
    }
    ~A(){
        delete buffer;
        cout<<"A destory function."<<endl;
    }
};

A foo(int a, int b){
    int c = a + b;
    return A(c);
}

int main(){
    A a(0);
    a = foo(4, 5);
    cout<<a.val<<endl;
    return 0;
}

执行上述代码,输出为:

A construct function.
A construct function.
A operator function.
A destory function.
9
A destory function.

可以看到,调用了两次构造函数,一次是在main()函数中初始化a,另一次是在foo()函数中构造临时变量(右值)。调用了一次重载赋值运算符,在给a赋值的过程中。

实际上,下面两种方式也是一样的:

a = foo(4, 5);
a = A(4+5);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值