2013-11-28 31 views
0

我目前正在試圖將我的程序中的一個矩陣與一個常量相乘,但由於沒有現有的方法可以做,所以我想我必須重載一個運算符等。但是因爲我已經把它重載了一次「*」操作符。它還需要從左側而不是從右側取值或更具體地說是常數。我如何繼續?試圖用常量乘以矩陣,重載算子兩次?

所有幫助表示讚賞!

重載運算符*

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

只需重載操作符並編寫一個將float作爲參數的版本。 – Danstahr

回答

2
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! 
} 
+0

爲什麼非會員需要? –

+1

@AbhishekBansal:由於C++的工作原理,第一個需要非成員。第二個可以成爲會員,但這是一個糟糕的設計! – Nawaz

+0

爲什麼不能像我的答案中的方式? (我確定一定有什麼問題,但我不明白) –