C ++重载运算符[] [] [英] C++ overload operator [ ][ ]

查看:264
本文介绍了C ++重载运算符[] []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类CMatrix,其中是值的数组的双指针。

I have class CMatrix, where is "double pointer" to array of values.

class CMatrix {
public:
    int rows, cols;
    int **arr;
};

我只需要键入以下内容来访问矩阵的值:

I simply need to access the values of matrix by typing:

CMatrix x;
x[0][0] = 23;

我知道如何使用:

x(0,0) = 23;

但我真的需要这样做。任何人可以帮助我吗?请?

But I really need to do that the other way. Can anyone help me with that? Please?

感谢大家的帮助,我这样做了...

Thank you guys for help at the end I did it this way...

class CMatrix {
public:
   int rows, cols;
   int **arr;

public:
   int const* operator[]( int const y ) const
   {
      return &arr[0][y];
   }

   int* operator[]( int const y )
   {
      return &arr[0][y];
   }

   ....

帮助我真的很感激它!

推荐答案

没有 operator [] [] 在C ++中。但是,您可以重载 operator [] 以返回另一个结构,并且在重载 operator [] 效果。

There is no operator[][] in C++. However, you can overload operator[] to return another structure, and in that overload operator[] too to get the effect you want.

这篇关于C ++重载运算符[] []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆