2011-04-29 72 views
1

嗨,我 很困惑,如何進入像這樣的一個重載的模板函數:使用功能,如接入重載模板函數

template <typename T> 
friend istream& operator>> (istream& in, Matrix& right) 
{ 
     for(int i=0; i<right.rows*right.cols; i++) 
     cin >> right.elements[i]; 
} 

template <typename T> 
Matrix(T r, T c) {rows=r; cols=c; elements=new T[r*c];} 

我是能做

Matrix <double> test(number, number) 

例如,但我不知道如何使用模板>>操作符(或< <或*或+ ..)任何幫助將不勝感激。謝謝!

+0

您需要添加更多的上下文,特別是類模板聲明,包括成員屬性和現有代碼*,它實際上是*在類模板中(或不在其中)。 – 2011-04-29 07:44:58

回答

0

我假設你正在聲明具有類型參數T類模板Matrix,並且要使用已定義的operator>>(你應該讓這問題更清楚了):

template <typename T> 
class Matrix { 
    int rows, cols; 
    T* elements; 
public: 
    Matrix(int c, int r);  // Do you really want the number of 
            // rows/columns to be of type `T`?? 

    // Note: removed template, you only want to befriend (and define) 
    // a single operator<< that takes a Matrix<T> (the <T> is optional 
    // inside the class braces 
    friend std::istream& operator>>(std::istream& i, Matrix& m) 
    { 
     // m.rows, m.cols and m.elements is accessible here. 
     return i; 
    } 
}; 

然後使用起來非常簡單:

Matrix<double> m(1, 2); 
std::cin >> m; 

這不是唯一的選擇,它只是最常見的選擇。通常情況下,類模板可以與上面代碼中的單個(非模板化)函數(認爲是operator<<operator>>作爲函數)相關聯,或者它可能希望與一個函數模板(所有實例化)或特定的實例化函數模板。

我寫了一個關於不同選項和行爲的長篇解釋here,我建議您閱讀它。

+0

對不起,這沒有奏效。它聲稱right.cols,right.rows ...無法訪問沒有模板類型T行 – pauliwago 2011-04-29 07:35:10

+0

@pauliwago:你應該真的添加封閉的類模板聲明和成員聲明與上下文。否則,您要求在燈光關閉的房間內搜索物體。你是在'Matrix'類模板中定義運算符嗎? – 2011-04-29 07:41:25

0

好了,訪問的唯一方法是這樣的:

operator>> <YourType> (istream, param); 

但當然違背了操作符重載的所有優點。所以這個運算符定義有問題。也許矩陣是一個模板類型,它應該是

template <typename T> 
operator>>(istream & in, Matrix<T> & right); 

我看不到模板參數在您的運算符定義中,所以它有什麼問題。