【发布时间】:2012-08-21 08:36:00
【问题描述】:
在Effective C++ Item 03 中,尽可能使用 const。
class Bigint
{
int _data[MAXLEN];
//...
public:
int& operator[](const int index) { return _data[index]; }
const int operator[](const int index) const { return _data[index]; }
//...
};
const int operator[] 确实与 int& operator[] 不同。
但是呢:
int foo() { }
和
const int foo() { }
好像它们是一样的。
我的问题是,为什么我们使用const int operator[](const int index) const 而不是int operator[](const int index) const?
【问题讨论】:
-
好问题 - 虽然在这种情况下,该方法通常不会在两种情况下都返回引用吗?
-
好问题。我建议您将其更改为
int operator[](int i)而不是const int operator[](const int i)。 -
@KenWayneVanderLinde,不。调用的方法取决于我们是否有
Bigint&或a const Bigint&。 -
@AlexanderChertov no:他问的是返回类型,而不是参数类型,所以问题应该只关注这个
-
为什么?我个人想知道为什么有人会有
const int i参数。
标签: c++