我正在尝试创建一个使用运算符 [] 的类,例如
MyClass[x][y]
它应该根据我在类中定义的函数中调用的内容返回一个值。到目前为止我所拥有的是:
我的类.h
class MyClass{
public:
// return one value of the matrix
friend double operator[][] (const int x, const int y);
}
我什至不认为我的语法是正确的,我如何在 MyClass.cpp 中编写这个函数来定义它应该返回什么值?
是这样的:
MyClass::friend double operator[][] (const int x, const int y)
{
// insert code here
}
试过了,但一直报错。我相信那里一团糟......
非常感谢,
最佳答案
重载 operator()
绝对是最干净的方法。
但是,请记住这是 C++,您可以根据自己的意愿改变语法 :)
特别是,如果你坚持要使用myclass[][]
,你可以通过声明一个“中间类”来实现,这里有一个例子:
#include <iostream>
using std::cout;
using std::endl;
class MyClass {
public:
using IndexType = int;
using ReturnType = double;
// intermediate structure
struct YClass {
MyClass& myclass;
IndexType x;
YClass (MyClass& c, IndexType x_) : myclass(c), x(x_) {}
ReturnType operator[](IndexType y_) { return myclass.compute(x, y_); }
};
// return an intermediate structure on which you can use opearator[]
YClass operator[](IndexType x) { return {*this, x}; }
// actual computation, called by the last "intremediate" class
ReturnType compute(IndexType x, IndexType y) {
return x * y;
}
};
int main()
{
MyClass myclass;
cout << myclass[2][3] << endl; // same as: cout << myclass.compute(2, 3) << endl;
}
关于c++ - 如何链接多个运算符[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33363510/