【问题标题】:Multiple operands for overloaded * operator重载 * 运算符的多个操作数
【发布时间】:2018-02-11 18:40:20
【问题描述】:

我想重载 * 运算符有两个目的:

第一个目的:

m4 * 3.5; //m4 is a matrix object

上面对这个函数有效,这里的实现绝对没问题

Matrix operator *(const double n)

但是,当我尝试相反时,即

3.5 * m4;

我收到一条错误消息,提示没有匹配的函数。所以我为这个特殊情况制作了这个函数

Matrix operator *(const double n, Matrix &obj)
{
    for(unsigned int i = 0; i < rows; i++ )
    {
        for(unsigned int j = 0; j < cols; j++)
        {
            obj[i][j] =  obj[i][j] * n;
        }

    }

    return *this;
}

现在,我得到了错误:

错误:'Matrix Matrix::operator*(double, Matrix&)' 必须采用零或一个参数 矩阵运算符 *(const double n, Matrix &obj);

error: no match for ‘operator*’(操作数类型是 ‘double’ 和 ‘矩阵’)
cout

我不知道如何克服操作数的问题!

不幸的是,我不能使用 BLAS、Eigen 等。这项任务要求我们在这个矩阵废话中挣扎。

【问题讨论】:

  • 请不要仅仅为了纠正我的语法和大写错误而编辑我的帖子。我来这里是为了编程帮助而不是英语课。这些错误并没有妨碍任何人理解我的代码!

标签: c++ matrix operator-overloading overloading


【解决方案1】:

您已使Matrix operator *(const double n, Matrix &amp;obj) 成为Matrix 的成员,这意味着它具有this 的隐式第一个参数。你需要做的是让它成为一个非成员函数。

还要注意它不应该修改操作数,所以你应该通过 const 引用传递Matrix

Matrix operator *(const double n, const Matrix &obj);

你的第一个重载也可以这样说,它应该是一个 const 成员函数

Matrix operator *(const double n) const;

或非会员:

Matrix operator *(const Matrix& mat, const double n);

【讨论】:

  • 当我将它设为非成员函数时,它给了我这个错误:“未定义对 `operator*(double, Matrix const&)' 的引用”,我还转发声明了 Matrix 类,但这并没有似乎没有帮助。
  • @Jaydie 你犯了其他错误。 SO 有很多关于未定义引用的 Q/As。
猜你喜欢
  • 1970-01-01
  • 2017-06-30
  • 2014-02-08
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
  • 2013-04-21
相关资源
最近更新 更多