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; }
相关文章推荐
- C++中4种强制类型转化。static_cast,const_cast,reinterpret_cast,dynamic_cast
- C/C++—— C++中函数重写和函数重载
- C语言所写的简单的贪吃蛇代码
- 猜数字(c语言实现)
- C++ 类型转换构造函数
- C++中的类模板详细讲述
- [转载]C++中类的组合
- C/C++—— C++中定义虚析构函数的原因
- C语言一些关于位操作符的小练习
- C++ 构造函数
- C/C++—— C++中构造函数不能是虚函数的原因分析
- C++ error: default argument given for parameter 1
- Count Primes
- 左旋转字符串m位
- CSP考试 2013年12月第3题 最大矩形 C语言实现
- 设计模式C++工厂模式
- C++的tie()函数
- [C++]字符串流 istringstream 和 ostringstream 的用法
- C/C++—— 在构造函数中调用虚函数能实现多态吗(Vptr指针初始化的过程分析)
- C++:标准IO(输入输出)