gpt4 book ai didi

c++ - 尝试将矩阵与常量重载运算符相乘两次?

转载 作者:行者123 更新时间:2023-11-28 03:03:10 26 4
gpt4 key购买 nike

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

感谢所有帮助!

重载的 * 运算符

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

关于c++ - 尝试将矩阵与常量重载运算符相乘两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com