【问题标题】:Overloading Operator [][] c++ [duplicate]重载运算符 [][] C++ [重复]
【发布时间】:2016-09-26 15:25:30
【问题描述】:

要有一个类:

template <class A_Type,int sizeA,int sizeB>
class Matrix {

    A_Type myMatrix[sizeA][sizeB];
    int sizeA_Val;
    int sizeB_Val;
public:
    Matrix();
    Matrix(A_Type val);

    int getSizeA()const{return sizeA_Val;} ;
    int getSizeB()const{return sizeB_Val;};

    A_Type mini() const;
    double avg() const;


    Matrix operator+(const Matrix& b)
          {
             Matrix<A_Type,sizeA,sizeB> tmpNew;
             for (int i=0;i<sizeA;i++){
                 for (intj=0;j<sizeB;j++){
                     tmpNew[i][j]=myMatrix[i][j]+b[i][j];
                 }
             }

             return box;
          }
};

它在 Matrix operator+(const Matrix&amp; b) 函数之外工作

我想让它工作,因为我想创建运算符 [][],这可能吗?

我想例如如果我看到 mat[i][j] 它将返回 mat->myMatrix[i][j] 中的值

有可能吗?

【问题讨论】:

  • 顺便说一句,Matrix::operator+ 可以访问Matrix::myMatrix

标签: c++ operator-overloading


【解决方案1】:

有可能吗?

不,不是没有中间行帮助器类,它也为operator[]() 提供重载。

问题是是否值得优先编写调用运算符重载:

T operator()(int,int) {
    // ...
}

【讨论】:

    猜你喜欢
    • 2011-10-27
    • 2012-12-22
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 2016-06-27
    • 2020-01-14
    相关资源
    最近更新 更多