2012-02-23 68 views
0

好吧我有點卡住試圖超載模板類的< <運算符。要求是運算符必須調用爲這個類定義的void打印函數。operator << overloading調用打印函數的麻煩

下面是從模板頭重要的東西:

template <class T> 
class MyTemp { 
public: 
    MyTemp();   //constructor 

    friend std::ostream& operator<< (std::ostream& os, const MyTemp<T>& a); 

    void print(std::ostream& os, char ofc = ' ') const; 

,這裏是我的打印功能基本上它是一個載體,並打印最後一個元素到第一個:

template <class T> 
void Stack<T>::print(std::ostream& os, char ofc = ' ') const 
{ 
    for (int i = (fixstack.size()-1); i >= 0 ; --i) 
    { 
     os << fixstack[i] << ofc; 
    } 
} 

,這裏是我如何有運營商< <過載:

template <class T> 
std::ostream& operator<< (std::ostream& os, const Stack<T>& a) 
{ 
    // So here I need to call the a.print() function 
} 

但我收到「無法解析的外部符號」錯誤。所以真的我想我有兩個問題。第一,是解決上述錯誤的方法。其次,一旦這個問題得到解決,我會在< <過載內調用a.print(os)?我知道它需要返回一個ostream。任何幫助將不勝感激!

+1

閱讀此常見問題解答:http://www.parashift.com/c++-faq/templates.html#faq-35.16 – 2012-02-23 07:20:43

+0

您在第一個片段中調用類模板「MyTemp」,在其他片段中調用「Stack」。你是否在你的真實代碼中這樣做? – 2012-02-23 07:21:57

回答

2

最簡單的做法是將print保留爲公開狀態(因爲它在您的示例中),所以操作員不需要成爲朋友。

template <class T> 
class MyTemp { 
public: 
    void print(std::ostream& os, char ofc = ' ') const; 
}; 

template <class T> 
std::ostream& operator<< (std::ostream& os, const MyTemp<T>& a) { 
    a.print(os); 
    return os; 
} 

如果你需要它是私有的,那麼你就需要聲明的正確的模板專業化是朋友 - 你friend聲明聲明在周圍的命名空間的非模板運營商,而不是一個模板。不幸的是,作出一個模板,你需要事先聲明它的朋友:

// Declare the templates first 
template <class T> class MyTemp; 
template <class T> std::ostream& operator<< (std::ostream&, const MyTemp<T>&); 

template <class T> 
class MyTemp { 
public: 
    friend std::ostream& operator<< <>(std::ostream& os, const MyTemp<T>& a); 
    // With a template thingy here ^^ 

private: 
    void print(std::ostream& os, char ofc = ' ') const; 
}; 

template <class T> 
std::ostream& operator<< (std::ostream& os, const MyTemp<T>& a) { 
    a.print(os); 
    return os; 
} 

或者你可以定義運營商在線:

template <class T> 
class MyTemp { 
public: 
    friend std::ostream& operator<<(std::ostream& os, const MyTemp<T>& a) { 
     a.print(os); 
     return os; 
    } 

private: 
    void print(std::ostream& os, char ofc = ' ') const; 
}; 

對於你最後一個問題:

其次,一旦固定,我會在<<超載內撥打a.print(os)?我知道它需要返回ostream

它確實需要返回一個ostream - 因此只需返回傳入的參數即可,如我的示例代碼。

+0

啊完美的作品謝謝你!需要處理我的模板技能。我將來會記住這些信息。 – Doug 2012-02-23 23:22:07

0

由於您的print成員函數是公開的,因此不需要聲明operator<<friend

意識到你正在使用類Stack是你超載,以上MyTemp ...

+0

我的糟糕之處並不在於我的代碼中,我嘗試將所有Stack的實例更改爲MyTemp,以避免混淆,錯過了其中的一個。不過謝謝。 – Doug 2012-02-23 23:21:49

1

此錯誤意味着有可能不是什麼變量是ü得到這些linker.on識別的符號錯誤 也請檢查堆棧,因爲有一個std :: stack類可用。