尝试将矩阵与常数重载运算符相乘两次

Trying to multiply a matrice with a constant, overload operator twice?

本文关键字:两次 运算符 重载 常数      更新时间:2023-10-16

我目前正在尝试将程序中的一个矩阵与常数相乘,但由于没有现有的方法可以做到这一点,我想我必须重载一个运算符或类似的运算符。但由于我已经超载了一次"*"运算符。它还需要从左边而不是从右边取值,或者更具体地说是常数。如何继续?

感谢所有的帮助!

过载*操作员

matrix operator * (matrix const arg){
    double sum = 0;
    int x = 0;
    int rowY = 0;
    int rowX = 0;
    this->matrix_array_multiply = new double[row*arg.col];
    for (int position = 0; position < row*arg.col; position++, x++){
        if (arg.matrix_array[x*arg.row] == (arg.matrix_array[arg.row*arg.col])){
            //If last number in second matrix, reset these values and proceed with next row of Y-values.
            x = 0;
            rowY++;
        }
        for (int y = 0; y < arg.row; y++, rowX++){
            sum = sum + (matrix_array[y + (rowY*col)]) * (arg.matrix_array[x + (rowX*arg.col)]);
        }
        matrix_array_multiply[position] = sum;
        rowX = 0;
        sum = 0;
    }
    matrix new_matrix_multiply(matrix_array_multiply, row, arg.col); //Create new instance of new matrix.
    return new_matrix_multiply; //Return new matrix.
}

不同矩阵和运算符的用法:

int main () {
double a[] =  { 3, 0, 3, 4,
                3, 4, 2, 4,
                5, 3, 2, 1 };
double b[] =  { 6, 3, 5, 7,
                9, 8, 6, 4,
                6, 5, 3, 1 };
double c[] =  { 1, 2, 3, 4,
                5, 6, 7, 8,
                9, 2, 1, 1,};
double d[] =  { 6, 5, 4, 3,
                2, 1, 0, 1,
                2, 3, 4, 5,
                6, 7, 8, 9};
double e[] = { 1, 2, 1,
               3, 5, 7,
               9, 7, 3};
matrix matrix1(a, 3, 4); //Instance of the class matrix: array, rows, columns.
matrix matrix2(b, 3, 4);
matrix matrix3(c, 3, 4);
matrix matrix4(d, 4, 4);
matrix matrix5(e, 3, 3);
matrix matrix6 = (matrix1 + matrix2);
matrix matrix7 = (matrix2 - matrix1);
matrix matrix8 = (matrix3 * matrix4);
matrix matrix9 = ~matrix5;
matrix matrix10 = (5.7 * matrix5); // Error: no operator "*" matches these operands, operand types are: double * matrix 
}

注意:我刚开始学习c++,这是家庭作业的一部分。

matrix matrix10 = (5.7 * matrix5);

为了实现这一点,您必须定义一个带有以下签名的免费函数:

matrix operator*(double c, matrix const & m) //non-member function
{
   //your code
}

同样,你也想定义这个:

matrix operator*(matrix const & m, double c)
{
    return c * m; //call the other overload!
}