操作符重载= and[]

Operator overloading = and []

本文关键字:and 重载 操作符      更新时间:2023-10-16

现在,我必须写

st[1];
st = 5;

我必须在我的代码中改变什么才能做到这一点:

st[1] = 5;

#include <iostream>
using namespace std;
class A
{
public:
  A(){this->z = 0;}
  void operator = (int t)  { this->x[this->z] = t+10; }
  int& operator [] (int t) { this->z=t; return this->x[t]; }
private:
  int x[2];
  int z;
};
void main()
{
  A st;
  st[0]=9;
  cout<<st[0]; 
  system("pause");
}

乌利希期刊指南:现在我看到9而不是19。

内置运算符=需要左值作为其左操作数。因此,为了编译这条语句:

st[1] = 5;

您需要将operator []的返回类型从int更改为int&:

    int& operator [] (int t) { return this->x[t]; }
//  ^^^^

您还可以提供const重载,如果调用operator []的对象是const,它将返回对const的引用:

    int const& operator [] (int t) const { return this->x[t]; }
//  ^^^^^^^^^^                     ^^^^^