Max*_*xpm 4 c++ operator-overloading return-type
假设我有一个包含MyContainerClass整数的容器类.该[]运营商,如你所知,也可以被重载以便如果容器是一个规则的阵列,用户可以更直观地访问值.例如:
MyContainerClass MyInstance;
// ...
int ValueAtIndex = MyInstance[3]; // Gets the value at the index of 3.
Run Code Online (Sandbox Code Playgroud)
显而易见的返回类型operator[]是int,但是用户将无法执行以下操作:
MyContainerClass MyInstance;
MyInstance[3] = 5;
Run Code Online (Sandbox Code Playgroud)
那么,返回类型应该operator[]是什么?
Joh*_*itb 15
明显的返回类型是int&:)
为了更好的阐述:
int &operator[](ptrdiff_t i) { return myarray[i]; }
int const& operator[](ptrdiff_t i) const { return myarray[i]; }
// ^ could be "int" too. Doesn't matter for a simple type as "int".
Run Code Online (Sandbox Code Playgroud)