2012-05-13 53 views
1

我有一些關於操作符重載的問題。我到處尋找,但無法找到適合此錯誤的解決方案。下面是我的一些代碼部分:錯誤t 2錯誤C2679:二進制'/':沒有發現操作符需要類型的右側操作數(或沒有可接受的轉換)

Matrix<type> Matrix<type>::operator/(const Matrix& denom){ 

if(num_of_rows != denom.num_of_rows || num_of_cols != denom.num_of_cols) 
    throw string("Unable to divide (Different size)."); 
if(denom.contains(0)) 
    throw string("Unable to divide (Divide by zero)."); 

for(int i = 0; i < num_of_rows; i++) 
    for(int j = 0; j < num_of_cols; j++) 
     values[i][j] /= denom.values[i][j]; 
        // I KNOW THIS IS NOT HOW TO DIVIDE TWO MATRICES 

return *this; 
} 

void Matrix<type>::operator=(const Matrix& m) const { 

delete [][] values; 
num_of_rows = m.num_of_rows; 
num_of_cols = m.num_of_cols; 
values = new type*[num_of_rows]; 

for(int i = 0; i < num_of_rows; i++){ 
    *(values + i) = new type[num_of_cols]; 
    for(int j = 0; j < num_of_cols; j++) 
     values[i][j] = m.values[i][j]; 
} 
} 

這是Matrix類和構造函數有兩個參數:

class Matrix{ 

private: 
    type** values; 
    int num_of_rows, num_of_cols; 

public: 
    Matrix(){} 
    Matrix(int, int); 
    type getElement(int, int); 
    void print(); 
    bool contains(type); 
    Matrix<type> operator/(const Matrix&); 
    void operator=(const Matrix&) const; 
}; 

template <class type> 

Matrix<type>::Matrix(int rows, int cols){ 

values = new type*[rows]; 
num_of_rows = rows; 
num_of_cols = cols; 

for(int i = 0; i < rows; i++){ 
    *(values + i) = new type[cols]; 
    for(int j = 0; j < cols; j++){ 
      type random = (type)rand()/3276.71; 
     values[i][j] = random; 
    } 
} 
} 

這一塊的主代碼給出了這樣的錯誤:

srand(time(NULL)); 
Matrix<int> m1(3,5); // creating some objects 
Matrix<double> m2(3,5); // matrices’ elements are assigned randomly from 0 to 10 
Matrix<double> m3(5,5); 
Matrix<double> m4(5,6); 
if(!(m2.contains(0))){ 
    Matrix<double> m8(3,5); 
    m8=m1/m2; // THIS LINE GIVES ERROR 
    m8.print(); 
} 
+0

與手頭無關,但您的'operator ='對於自我分配並不安全。習慣上將值複製到臨時數組中,然後在最後刪除舊緩衝區之前用'values'交換指向該數組的指針。 –

回答

4

m1有類型Matrix<int>,所以當查找合適的過載operator/我們發現:

Matrix<int> Matrix<int>::operator/(const Matrix& denom); 

請注意,此處的參數類型Matrix使用了所謂的注入類名稱。這意味着Matrix在這種情況下代表Matrix<int>,因爲這是相關的(模板)類。但是m2,對operator/的調用的參數具有類型Matrix<double>。沒有從Matrix<double>Matrix<int>的合適轉換,因此該呼叫無效。

一個可能的解決方法是改變operator/也成爲一個模板:(我也採取了固定運營商,以更好地反映它的實際做什麼的自由)

// Declared inside Matrix<type>: 
template<typename Other> 
Matrix& operator/=(Matrix<Other> const& other); 

但是你」然後遇到問題,您正在使用Matrix<int>(調用operator/的結果)分配給m8,其類型爲Matrix<double>。所以也許你需要一個operator=做轉換(在這種情況下,我會推薦一個轉換構造函數,或者甚至可能只是一個沒有轉換operator=的轉換構造函數)。

+0

非常感謝,我的工作。 – burakongun

0

錯誤消息很清楚地表明,您還沒有定義一個將這兩種類型作爲參數傳遞的除法運算符。看代碼摘錄是這樣的情況:有一個運營商採取兩個Matrix<T>但沒有采取Matrix<T1>Matrix<T2>(對於不同的類型T1T2)。

順便說一句,你的問題是什麼?

相關問題