关于下标操作符重载,书C++ Primer例子错误,求解答

zh359780498 zh359780498 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
C++ Primer 第四版
14.5. 下标操作符
下面是书本源码,稍作修改,只为初始化。。

class Foo 
{
public:
Foo()
{
for (int i = 0; i < 10; i++)
{
data.push_back(i);
}
}
int &operator[] (const size_t);
const int &operator[] (const size_t) const;
// other interface members
private:
std::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
}
const int& Foo::operator[] (const size_t index) const
{
return data[index]; // no range checking on index
}

int _tmain(int argc, _TCHAR* argv[])
{
Foo a;
a[0] = 145; // 作左值
int n = a[0]; // 作右值
return 0;
}


发现两次都是调用的 int& Foo::operator[] (const size_t index)
何时才能调用 const int& Foo::operator[] (const size_t index) const
求正解。
...全文

相关推荐

评论 9
收藏 已收藏
分享
返回顶部
zh359780498
C++ 语言 65,214 成员 250,514 内容