我目前正在试图将我的程序中的一个矩阵与一个常量相乘,但由于没有现有的方法可以做,所以我想我必须重载一个运算符等。但是因为我已经把它重载了一次“*”操作符。它还需要从左侧而不是从右侧取值或更具体地说是常数。我如何继续?试图用常量乘以矩阵,重载算子两次?
所有帮助表示赞赏!
重载运算符*
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++,这是一门功课的一部分。
只需重载操作符并编写一个将float作为参数的版本。 – Danstahr