c++ - 如何重载 operator[] 以允许 `object[a] = b` ?

标签 c++ operator-overloading

可以重载 operator[] 以在括号中接受一个参数。但是,如何重载此运算符以允许用户键入 object[a] = b

最佳答案

您返回对您的项目的引用,例如:

A &operator[](int pos) { return list[pos]; }

所以当你说 object[a]=b; 它实际上被翻译成:

A &tmp=object[a];
tmp=b;

或者更明确地说:

A *tmp=object[a];          // more or less a pointer
*tmp=b;                    // you replace the value inside the pointer

关于c++ - 如何重载 operator[] 以允许 `object[a] = b` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26317574/

相关文章:

c++ - 使用 boost::thread 崩溃

c++ - Qt/OpenGL : Am I using PBO correctly ?

C++ 运算符使用友元函数重载。尝试添加多个对象失败

c++ - 在可变参数模板中使用声明

c++ - 为稀疏 vector 重载运算符 []

c++ - 重载运算符--无法在赋值中将对象转换为基类型

c++ - 如何在类中创建不可变的静态公共(public)对象?

c++ - C/C++ 指向一维数组变量的指针

c++ - 为什么会出现错误 "no matching function for call to ' A(A<...auto...> )'"?

c++ - 错误 : postfix ‘unaryOperators unaryOperators::operator++(const unaryOperators&)’ must take ‘int’ as its argument