我正在尝试将我程序中的一个矩阵与常量相乘,但由于没有现有方法可以做到这一点,我想我必须重载运算符等。但是因为我已经将“*”运算符重载了一次。它还需要从左侧而不是从右侧获取值或更具体的常量。我该怎么办?
感谢所有帮助!
重载*运算符
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 ++,这是作业的一部分。
答案 0 :(得分:2)
matrix matrix10 = (5.7 * matrix5);
为此,您需要使用此签名定义 free 函数:
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!
}