《c++ primer》 14.5 下标操作符
2015-11-30 14:50
337 查看
定义下标操作符的复杂地方在于:它在用作赋值的左右操作数时都应该能表现正常
重载下标操作符的一大好处便是对对象内部的容器可以像访问数组元素一样进行读写
为什么要返回引用?
#include <vector>
using std::vector;
#include <iostream>
using std::cout; using std::endl;
class Foo {
public:
Foo(): data(100) { for (int i = 0; i != 100; ++i) data[i] = i; }
int& operator[](const size_t);
//const int operator[](const size_t) const;
// other interface members
private:
vector<int> data;
// other member data and private utility functions
};
int& Foo::operator[](const size_t index)
{
return data[index]; // no range checking on index
}
int main() {
Foo f;
cout << f[50] << endl; //相当于cout << f.operator[](50) << endl;
f[50] = 90; //相当于f.operator[](50) = 90;
cout << f[50] << endl;
system("pause");
return 0;
}
不返回引用时:
f[50] = 90;(Error:表达式必须是可以修改的左值)
此时利用下标操作符只能读取data的i50号元素,但不可以修改,即不可以写。
f[50]相当于调用了成员函数f.operator[](50),由于不是返回引用,那么函数在返回的地方会创建一个临时整形变量,并用f.data[50]进行初始化,所以即使可以赋值,也仅仅是对临时对象进行赋值。但如果该函数返回的是引用的话,那么函数调用结束后并不会创建临时变量保存运算结果,而是直接把f.data[50]放在调用结束处,因此是可以改写对象的内部状态的。这便是返回引用的好处。
转自:http://blog.csdn.net/bruce128/article/details/7268515
重载下标操作符的一大好处便是对对象内部的容器可以像访问数组元素一样进行读写
为什么要返回引用?
#include <vector>
using std::vector;
#include <iostream>
using std::cout; using std::endl;
class Foo {
public:
Foo(): data(100) { for (int i = 0; i != 100; ++i) data[i] = i; }
int& operator[](const size_t);
//const int operator[](const size_t) const;
// other interface members
private:
vector<int> data;
// other member data and private utility functions
};
int& Foo::operator[](const size_t index)
{
return data[index]; // no range checking on index
}
int main() {
Foo f;
cout << f[50] << endl; //相当于cout << f.operator[](50) << endl;
f[50] = 90; //相当于f.operator[](50) = 90;
cout << f[50] << endl;
system("pause");
return 0;
}
不返回引用时:
f[50] = 90;(Error:表达式必须是可以修改的左值)
此时利用下标操作符只能读取data的i50号元素,但不可以修改,即不可以写。
f[50]相当于调用了成员函数f.operator[](50),由于不是返回引用,那么函数在返回的地方会创建一个临时整形变量,并用f.data[50]进行初始化,所以即使可以赋值,也仅仅是对临时对象进行赋值。但如果该函数返回的是引用的话,那么函数调用结束后并不会创建临时变量保存运算结果,而是直接把f.data[50]放在调用结束处,因此是可以改写对象的内部状态的。这便是返回引用的好处。
转自:http://blog.csdn.net/bruce128/article/details/7268515
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性
- C++ Custom Control控件向父窗体发送对应的消息