【问题标题】:Overloading '=' to make '+' work with matrices重载 '=' 以使 '+' 与矩阵一起使用
【发布时间】:2014-03-24 10:24:55
【问题描述】:

这是一个带有对象“矩阵”的类,它存储一个二维动态数组。我需要能够添加 2 个矩阵并将元素的总和放入结果矩阵中。 (即:c[1][1] 将等于 a[1][1] + b[1][1])。 但我想通过以下方式实现它:

Square_Matrix a,b,c;
c = a + b;

这是我的两个重载运算符,'=' 一个在 '+' 之外工作正常(所以 a = b = c 工作正常,矩阵被复制过来)。不幸的是,我的 IDE 没有出现错误,程序只是关闭并显示“Square_Matrix 已停止工作”。我怎样才能解决这个问题?

我也不太确定我是否正确实现了我的 '+',有人说“return *this”不会做任何事情。

//.h file
Square_Matrix& operator=(const Square_Matrix& Par2);
Square_Matrix& operator+(const Square_Matrix& Par3);

//.cpp file    
Square_Matrix& Square_Matrix::operator=(const Square_Matrix& Par2){
    if (size != Par2.size){
        cout << "Matrices are of different size" << endl;
    } else {
        for (int i = 0; i < size; i++){
            for (int j = 0; j < size; j++){
                 matrix[i][j] = Par2.matrix[i][j];
            }
        }
    }
}

Square_Matrix& Square_Matrix::operator +(const Square_Matrix& Par3){
    Square_Matrix result;
    result.Set_Size(Par3.size);
    for (int i = 0; i < Par3.size; i++){
        for (int j = 0; j < Par3.size; j++){
            result.matrix[i][j] = Par3.matrix[i][j]+matrix[i][j];
        }
    }
return *this;
}

【问题讨论】:

  • 您的operator= 应以return *this; 结尾。您的 operator+ 应以 return result; 结尾,并且不应返回引用。
  • @remyabel:来自operator+?这不是不返回参考的原因。您不会返回引用,因为 operator+ 应该在函数本地创建一个新对象。如果你返回一个引用,那将是一个悬空引用。
  • 另见here(查找operator+operator+=的正确定义)
  • 抱歉打错了,我的 = 函数确实有返回 *this。并且返回结果似乎清除了错误,谢谢
  • @Foxic -首先,让 operator = 检查尺寸是对 operator = 应该做的事情的滥用。 operator= 应该有一个目的,而且只有一个目的,那就是制作副本。您无法编写“业务规则”,例如由于大小不匹配而无法制作副本。如果你想要一个检查大小的函数,那么为此目的创建另一个成员函数——不要为此使用 operator =。

标签: c++ matrix operator-overloading


【解决方案1】:

您的Square_Matrix&amp; Square_Matrix::operator=(const Square_Matrix&amp; Par2) 应该以

结尾
return *this;

你的Square_Matrix&amp; Square_Matrix::operator +(const Square_Matrix&amp; Par3)应该以

结尾
return result;

然后改变

Square_Matrix& Square_Matrix::operator +(const Square_Matrix& Par3)

Square_Matrix Square_Matrix::operator +(const Square_Matrix& Par3)

【讨论】:

  • 如果返回类型是引用,则运算符 + 不应返回“结果”。 “结果”是一个局部变量,就是UB返回一个局部变量的引用。
  • @PaulMcKenzie,你是对的。抱歉,我忘记添加最后一个要求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 2010-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-03
相关资源
最近更新 更多