C++ 中临时对象 和 const 对象 的一个区别
来源:互联网 发布:网络天才akinator很卡 编辑:程序博客网 时间:2024/04/30 01:07
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;}
0 0
- C++ 中临时对象 和 const 对象 的一个区别
- C++ const对象 和 C const对象的区别之一 —— 默认作用域
- C++中函数返回临时对象和本地对象的区别
- C++中函数返回临时对象和本地对象的区别
- C++中指针,引用与const,以及const中的临时量对象的探讨
- const对象的指针和const指针的区别
- 指向const对象的指针 和 const指针的区别
- 为什么不能从子函数中返回临时对象的指针和引用,却可以返回一个临时变量的值
- 函数返回的临时对象为const类型,const引用
- C++const对象和 引用
- C++const函数和const对象
- 【C++】const对象和const成员
- C++中类的const成员函数和const对象
- C++中 const对象和非const对象与const成员的关系
- c和c++中const的区别
- C和C++中const的区别
- c和c++中const的区别
- C和C++中const的区别
- android 滑动事件冲突解决 Touch事件处理机制
- [JAVA · 初级]:16.常用类
- 【HDU 1396】 【ZOJ 1629】 Counting Triangles
- 库和框架
- Linux进程间通信方式--本地socket
- C++ 中临时对象 和 const 对象 的一个区别
- csv文件中有行字符串中有,的读取方法
- [Sicily 1114 Food Cubes] 广度优先搜索
- J2EE轻量级框架--4.03学习心得
- 苦瓜降火
- 修改数据库字符集为'us7ascii'
- 个人向LaTex总结
- 什么是指针?
- IT 团队管理