C++ 中临时对象 和 const 对象 的一个区别

C++ 中临时对象和const对象的一个区别

const 对象特点

1,只能作为右值
2,只能调用对象的const方法

临时对象特点

1,只有作为为 const& 赋值 给其它对象
2,可以调用对象的非 const方法 //但是这样是无效的改变,修改信息会被丢失

解决方法

约定: 除赋值运算外的其他运算符在重载时返回const 临时对象
//ps:赋值运算返回对象引用,方便连缀表达式(如” (a=b).f()”)

code

#include <iostream>
#include <string>

using namespace std;

class A{
    int i;
public:
    A(int ii):i(ii){}
    A operator+(const A& r)
    {
        this->i += r.i;
        return *this;
    }
    A change(const int& ii)
    {
        return A(ii);
    }

    friend ostream& operator<<(ostream& os,const A& a)
    {
        return os << a.i;
    }
};

int main()
{
    string s1 = "a";
    string s2 = "b";
    string s3 = "ok";
    const string s4= "456";

    int i1 = 1;
    int i2 = 2;

    cout << ( (s1 + s2) = s3  )<<endl;

//    s4.assign("123"); //not ok
//    cout << (i1 + i2 = 3 )<<endl; //not ok 因为int只是内建类型 非类

    A n1 = A(3);
    A n2 = A(4);
    const A n3(5);
    cout << (n1 + n2).change(3) <<endl;
//    n3.change(7); //not ok
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值