是否可以定义一个operator[]
需要多个参数的重载?也就是说,我可以定义operator[]
如下:
//In some class
double operator[](const int a, const int b){
return big_array[a+offset*b];}
然后像这样使用它?
double b=some_obj[7,3];
是否可以定义一个operator[]
需要多个参数的重载?也就是说,我可以定义operator[]
如下:
//In some class
double operator[](const int a, const int b){
return big_array[a+offset*b];}
然后像这样使用它?
double b=some_obj[7,3];
不,你不能超载operator[]
接受多个论点。代替
double b = some_obj[7,3];
采用
double b = some_obj[7][3];
这个答案解释了如何创建代理对象以支持后者。
否则,您可以重载operator()
以获取 2 个参数。
不。在 C++ 中这样做的惯用方法是
double b = some_obj[7][3];
不,C++ 语法在
double b=some_obj[7,3];
逗号是逗号运算符,而不是分隔参数的逗号。
底线:不,不要混淆你的用户。
来自C++ 常见问题解答:
记住运算符重载的目的:降低使用您的类的代码的成本和缺陷率。如果你创建的操作符让你的用户感到困惑(因为它们很酷,因为它们使代码更快,因为你需要向自己证明你可以做到;不管为什么),你就违反了全部原因首先使用运算符重载。
你可以按照 Andrea 的建议去做,或者你可以重载operator()
接受两个参数:
// In some class
double operator()(const int a, const int b) {
return big_array[a + offset * b];
}
// Then use it like this:
double b = some_obj(7, 3);
更好的方法是operator()
. 更多详细信息在C++ FAQ中。
你不能,但在这种情况下,我认为一个函数会更好,因为你的操作员在做什么并不直观。