c++ - 重载 * 运算符的多个操作数

标签 c++ matrix operator-overloading overloading

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

第一个目的:

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;
}

现在,我得到了错误:

error: ‘Matrix Matrix::operator*(double, Matrix&)’ must take either zero or one argument Matrix operator *(const double n, Matrix &obj);

error: no match for ‘operator*’ (operand types are ‘double’ and ‘Matrix’)
cout << 3.5 * m4 << endl;

我不确定如何解决操作数的问题!

不幸的是,我不能使用 BLAS、Eigen 等。这项任务要求我们努力解决这个矩阵废话。

最佳答案

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

另请注意,它不应修改操作数,因此您应该通过 const 引用传递 Matrix:

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

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

Matrix operator *(const double n) const;

或者非成员(member):

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

关于c++ - 重载 * 运算符的多个操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46021571/

相关文章:

c++ - 受 'bad' 指令影响的变量

c++ - 将模板可变参数函数及其参数传递给函数

c++ - c++ 中的错误?-c++ 中的 set_difference 不返回 std::copy

matrix - 如何用矩阵的一些不连续的行和列形成子矩阵

c++ - 二进制 '[' : no operator found which takes a right-hand operand of type 'initializer list' (or there is no acceptable conversion)

C++ 指向重载索引的箭头 ( this->[ ] )

c++ - 指针 vector 的运算符<<重载抛出错误

C++ 将 float 转换为无符号字符?

c++ - 如何重载箭头取消引用运算符->() 不是针对实体对象而是针对指针

arrays - 已排序矩阵中的第 K 个最小元素