c++ - 如何链接多个运算符[]

标签 c++ class operator-overloading

我正在尝试创建一个使用运算符 [] 的类,例如

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[][],你可以通过声明一个“中间类”来实现,这里有一个例子:

Run It Online

#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/

相关文章:

c++ - operator new[] 定义分解

c++ - 使用 shared_ptr 作为输出参数

c++ - 运算符重载的基本规则和习惯用法是什么?

c++ - 类型转换运算符的特定事物

jquery - 将一个类添加到具有特定 ID 链接的标签

Java,从文件导入类

c++结构图中的值确实以隐藏的方式发生变化

c++ - 显式实例化具有通用类型的函数模板

c++ - 在初始案例后将值传递给变量