MMM*_*MMM 5 c++ pointers reference operator-overloading
我是C++的新手,我很抱歉因为这个问题,但这是一场斗争.如果有人能帮助我区分以下几行,我会很感激.
char& operator [](int); // write (why with reference?)
char operator [](int) const; //read (why without a reference?)
char const &operator[](int) const; // what is the difference compared to the previous line?
const char *& operator[] (const int* ); // is this also possible?
Run Code Online (Sandbox Code Playgroud)
您可能希望阅读运算符重载的概述.
那么,回顾一些适用的观点:
operator[]是始终非静态成员的一元函数.const限定的重载可以返回const引用或副本,以提供对相同元素的只读访问.
const如果无法动态生成元素,请使用-reference,特别是如果复制并不简单且便宜.顺便说一句:你真的希望const非const成员和非成员是类似的,所以non const可以是一个简单的内联函数,用适当的方式委托给另一个const_cast.
(不要反过来做,那是不允许的,也不是安全的.)
关于你的最后一行,用指针指向索引const int,并返回对指针的引用const char.
这是一个非常奇怪的返回值和索引,但如果你有一个有效的用途,为什么不呢?