【问题标题】:C++ Dynamic 2D-Array with pointers(Matrix)带指针的 C++ 动态二维数组(矩阵)
【发布时间】:2011-12-11 07:07:18
【问题描述】:

大家:

我正在创建一个程序,该程序能够为学校的课程创建矩阵并对其执行各种操作。它们要求我们使用适当的矩阵运算重载运算符。

我很难使用以下功能:

typedef double matrixType;


using namespace std;


class Matrix{
protected:
    int m,n; // m:row size n:column size
    matrixType **a; //Allows us to acces the a(ij) i,j position of the matrix


//==================================================
// (==Operator)Verifies if two given Matrices are equal
//==================================================

bool Matrix::operator==(const Matrix &B){

bool flag=false;


if(B.m ==m && B.n ==n){

    for (int row=0; row<m; row++) {
        for (int col=0; col<n; col++) {
            if (B[row][col] != a[row][col]) {
                flag=false;
            }
        }
    }
    flag= true;
}

else{
    flag=false;

}

return flag;


}

Xcode 在以下行警告我:

 if (B[row][col] != a[row][col])

type 'const Matrix' 不提供下标运算符

注意:此代码部分省略了函数头、构造函数和其他函数。

任何帮助将不胜感激。 谢谢。

【问题讨论】:

    标签: c++ pointers matrix operator-overloading


    【解决方案1】:

    boost::ublas::matrixboost::gil::view_typeOpenCV::Mat 等中获取提示,并使用operator(int,int) 代替下标运算符作为索引。它更容易实现、维护和调试。

    【讨论】:

    • 您好,感谢您的建议,我会尽快检查。现在我会用当前的实现来完成我的作业,因为我几乎已经准备好了。:)
    【解决方案2】:

    鉴于您的实现,它应该是if (B.a[row][col] != a[row][col])

    顺便说一句:如果您打算实现自己的矩阵类,您应该阅读this page

    【讨论】:

    • 他应该给它一个下标操作符。
    【解决方案3】:

    你的意思是

    if (B.a[row][col] != a[row][col]) {
                    flag=false;
    }
    

    如果你考虑一下,你就不能这样做

    if (B.a[row][col] != a[row][col]) {
                    return false;
    }
    

    并跳过标志变量altogeher?如果是,为什么,如果不是,为什么不(奖励你加分;)。

    如果你想真正做 B[][],你必须为你的班级实现 operator[]:

    matrixType* operator[](size_t index) 
    {
      return a[index];
    }
    

    【讨论】:

    • 我使用标志的原因是因为我担心在 IF 结构中只有 return 语句。我确实尝试在没有标志的情况下执行此操作,并从我的 IDE 中收到警告:“控件可能到达非无效函数的末尾”
    • @edu222 嗯,是的,你应该在最后加上另一个 return 语句。所以你需要 3: 1. 如果 Bm!=m&&B.n!=n 则返回 false 2. 如果 if 失败则返回 false (这也称为提前退出,想象一个 10^10x10^10 矩阵和所有不必要的比较,当它们在索引 0,0 处不同;) 3. 在方法结束时返回 true。
    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2013-04-06
    • 1970-01-01
    相关资源
    最近更新 更多