您的位置:首页 > 编程语言 > C语言/C++

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

2016-04-04 15:24 323 查看

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

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

临时对象特点

解决方法

code

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: