c++ operator[] 可以很好地编译多个参数,有没有办法避免这种情况?

c++ operator[] compiles fine with multiple arguments, is there a way to avoid that?

如果我有

int arr[10] = { 1,2,3,4,5 };
std::cout << arr[1,4] << "\n";

代码编译良好 returns 5 (arr[4])。即使在不同 类 中重载 operator[] 也是如此。换句话说,如果我有:

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

A a;
std::cout<<a[1,4];

我会得到4(a[4])。没有编译问题。在这种情况下,有没有办法通过编译错误来避免潜在的错误?

您在这里看到的是正在运行的 comma operator。评估左运算符,丢弃其结果,表达式的结果是右运算符。

Is there a way to avoid potential errors by a compilation error in such cases?

嗯..您可以为索引选择自定义类型并重载其逗号运算符。然而,这是not recommended

相反,请注意您的编译器警告。例如 gcc -Wall 警告此代码:

int main(){
    int x = (1,2);
}

<source>:4:14: warning: left operand of comma operator has no effect [-Wunused-value]

4 |     int x = (1,2);

  |              ^