c++ - 使用 operator[] 和 operator=

标签 c++ operator-overloading

给定一个重载“[]”运算符的简单类:

class A
{
  public:
    int operator[](int p_index)
    {
       return a[p_index];
    }

  private:
    int a[5];
};

我想完成以下任务:

void main()
{
   A Aobject;

   Aobject[0] = 1;  // Problem here
}

在这种情况下,如何重载赋值运算符“=”以与“[]”运算符一起使用?

最佳答案

您不要重载 = 运算符。你返回一个引用。

int& operator[](int p_index)
{
   return a[p_index];
}

确保同时提供一个 const 版本:

const int& operator[](int p_index) const
{
   return a[p_index];
}

关于c++ - 使用 operator[] 和 operator=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2766821/

相关文章:

c++ - 运算符重载 - 在左侧乘以 int 矩阵

c++ - 类内声明的友元运算符中左手参数的隐式转换

C++ 友元函数模板重载和 SFINAE 在 clang++、g++、vc++(C++14 模式)中的不同行为

c++ - 一个简单类模板的c++17中的 friend 流运算符

c++ - 用模板实现友元重载<<运算符

c++ - OpenCV - 让 slider 在视频播放期间更新其位置

c++ - pthreads 中的内存模型规范

c++ - OpenCL 找不到 ATI 卡

c++ - C 或 C++ 链接器中是否有任何类型检查?

c++ - 如何检查网站是否包含 C++ 中的字符串?