2012-02-23 84 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类可用。