运算符重载 - 将矩阵与左侧的 int 相乘 [英] operators overloading- multiply matrix with int in the left side

查看:62
本文介绍了运算符重载 - 将矩阵与左侧的 int 相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵和标量,让我们称之为矩阵 A.如果我将标量乘以矩阵,当标量在右侧 (2*A) 时,它将矩阵的所有索引乘以 2.但是当我将矩阵与左侧的标量相乘(A*2)它不起作用!(它应该像 2*A 一样).这是课程的一部分(有成员):

I have a matrix and scalar, lets call the matrix A. if I multiply the scalar to the matrix , when the scalar is on the right(2*A) it multiply all the indexes of the matrix by 2. BUT when I multiply the matrix with scalar on the left(A*2) it doesn't work!.(its should do as 2*A). This is part of class(with members):

class Mat
{
private:
    int **matArray;
    int rows;
    int cols;
    bool validMat;
public:
 .../*functions*/
};

这是正确乘法时的函数:

this is the function when of the right multiply:

Mat Mat::operator*(int scalarToMultiply){
    if(!validMat)
    {
        Mat resultOperator(0,0);
        return (resultOperator);
    }
    //Mat resultOperator(matToAdd.cols,matToAdd.rows);
    Mat resultOperator(cols,rows);
    for (int i=0; i<rows; i++){
        for (int j=0; j<cols; j++){
            resultOperator.matArray[i][j]=matArray[i][j]*scalarToMultiply;
        }
    }
    return (resultOperator);
}

相反我怎么做?

推荐答案

您可以将 operator* 定义为一个自由函数(在类之后):

You can define operator* as a free function (after the class):

Mat operator*(int scalarToMultiply, const Mat& mat) { ... }

如果您需要访问私有成员,请添加

And if you need access to the private members, make it a friend of your class by adding

friend Mat operator*(int scalarToMultiply, const Mat& mat);

到你的班级.

如果您打算编写operator*,您可能还想支持operator*=.为了让您的生活更轻松,您可以使用像 Boost.Operatorsdf.operators.这样,您只需实现基本运算符,而库会为您生成其余的.

If you plan to write operator*, you probably also want to support operator*=. To make your life easier, you can use libraries like Boost.Operators or df.operators. That way you only need to implement the basic operators and the libraries take care of generating the rest for you.

这篇关于运算符重载 - 将矩阵与左侧的 int 相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆