2011-04-25 109 views
0

有我的課的矩陣操作的一部分:C++,矩陣運算,與運營商的問題

class Matrix 
{ 
private: 
    std::vector < std::vector <T> > items;  
    const unsigned int rows_count;   
    const unsigned int columns_count;  

public: 
    Matrix (unsigned int m_rows, unsigned int m_columns); 
    Matrix (const Matrix <T> &M); 

    template <typename U> 
    Matrix <T> & operator = (const Matrix <U> &M); 

    template <typename U> 
    bool operator == (const Matrix <U> &M) const; 

    template <typename U> 
    bool operator != (const Matrix <U> &M) const ; 

    template <typename U> 
    Matrix <T> operator + (const Matrix <U> &M) const 
    ... 
}; 

其中

template <typename T> 
template <typename U> 
Matrix <U> Matrix <T> ::operator + (const Matrix <U> &M) const 
{ 
    Matrix <U> C (M); 

    for (unsigned int i = 0; i < rows_count; i++) 
    { 
     for (unsigned int j = 0; j < M.getColumnsCount(); j++) 
     { 
       C (i, j) = items[i][j] + M.items[i][j]; 
     } 
    } 

    return C; 
} 

template<class T> 
Matrix <T> :: Matrix (const Matrix <T> &M) 
    : rows_count (M.rows_count), columns_count (M.columns_count), items (M.items) {} 

但與以下運營商的一個問題:===!=

我想分配矩陣A

Matrix <double> A (2,2); 
Matrix <double> C (2,2); 

到矩陣B

Matrix <int> B (2,2); 

B = A; //Compiler error, see bellow, please 

其中A和B具有不同的類型。同樣的情況發生,共同矩陣運算

C = A + B //Compiler error, see bellow, please 

但是編譯器顯示此錯誤:

Error 23 error C2446: '!=' : no conversion from 'const Matrix<T> *' to 'Matrix<T> *const ' 

感謝您的幫助......

+2

你實際上並沒有發佈實施,任何能產生一個錯誤的功能。 – Puppy 2011-04-25 19:54:53

+0

@DeadMG:運營商+代碼中存在拼寫錯誤,我糾正了它... – Robo 2011-04-25 19:59:22

+1

錯誤消息引用的指針完全缺少您提供的代碼。注意'const Matrix *'相當於'Matrix const *'而不是'Matrix * const'。 – AProgrammer 2011-04-25 20:01:57

回答

1

有在代碼中的一些錯誤,你呈現,但是您應該計算出您提供的代碼片段,因爲錯誤似乎指向使用operator!=,而代碼使用operator=operator+

現在,由於一些具體問題:您聲明定義不同的運營商:

template <typename T> 
class Matrix { 
... 
    template <typename U> 
    Matrix<T> operator+(Matrix<U> const &) const; 
    // ^
}; 
template <typename T> 
template <typename U> 
Matrix<U> Matrix<X>::operator+(Matrix<U> const & m) const 
// ^

而且,在一般情況下,它更容易定義類的聲明作爲一個經驗法則裏面的模板成員。這實際上與您所遇到的問題無關,但在您真正瞭解提供確切的錯誤之前,需要涉及錯誤行和代碼(還請注意,如果您可以在一行中重現錯誤不要使用多於一個定義的運算符)...好吧,沒有更多的細節我真的幫不了多少忙。

+0

另一個問題是C(i,j)= items [i] [j] + M.items [i] [j]; 肯定C.items [i] [j] = ...的意圖。 – 2011-04-25 21:01:54

+0

我解決了operator =中的問題,並且它可以工作... – Robo 2011-04-25 21:25:58

+1

說你在不同的操作員(比你遇到的問題開始時)解決了問題幾乎沒有任何幫助。你至少應該提供什麼問題和解決方案,以便其他人通過SO來學習。 – 2011-04-26 07:26:19

0

正如其他人已經指出的那樣,由於您沒有提供產生錯誤''='',也不是'='的錯誤,因此很難知道問題是什麼。我的猜測是問題來自你的const數據成員。這可能會導致編譯器將Matrix類的所有實例解釋爲const對象,這會導致出現錯誤消息。當然,如果你的賦值運算符沒有考慮到這一點,那麼任何賦值都將失敗,儘管這樣的代碼可能不會編譯,而你的賦值也會失敗。

所以:拿出常量,看看會發生什麼。

此外,

C (i, j) = items[i][j] + M.items[i][j] 

應該肯定是

C.items[i][i] = items[i][j] + M.items[i][j] 
+0

這是隻有一半代碼的問題。我假設'items'是私有的,他可能已經提供了'operator()(int,int)'(或類似的東西)用於成員訪問,他會使用它。但是在一天結束時,任務的兩邊應該看起來相似(或者是[] []'或者都是'(,)') – 2011-04-26 07:24:43