2015-05-28 101 views
0

我有一个模板类,而当IM乳宁程序,它说错误LNK2019:解析外部符号

错误LNK2019:无法解析的外部符号“类的std :: basic_ostream> & __cdecl操作< <(类的std :: basic_ostream> &,class CSet &)“(?? 6 @ YAAAV?$ basic_ostream @ DU?$ char_traits @ D @ std @@@ std @@ AAV01 @ AAV?$ CSet @ H @@@ Z)在函数” public:void __thiscall Menu :: menu(void)“(?menu @ Menu @@ QAEXXZ)

关于我尝试使用的任何种类的数据结构,如果有人能向我解释为什么过载g的打印功能使得我很乐意听到这个错误。

template <class T> class CSet{ 
T* Array; 
int size; 
public: 
CSet() 
{ 
    Array = NULL; 
    size = 0; 
} 
CSet(CSet& other){ 
    size = other.size; 
    Array = new T[size]; 
    for (int i = 0; i < size; i++) 
     Array[i] = other.Array[i]; 
} 
friend ostream& operator <<(ostream& out, CSet& other); 
~CSet() 
{ 
    if (size > 0) 
     delete[] Array; 
} 
}; 


template <class T> ostream& operator <<(ostream& out, CSet<T>& other){ 
out << "("; 
for (int i = 0; i < other.size; i++){ 
    if (size>1) 
     out << other.Array[i] < ","; 
    else 
     out << other.Array[i]; 
} 
out << ")" << endl; 
return out; 
} 

回答

3

friend声明不声明函数模板,但对于类模板的每个实例的单独功能。因此,您定义的模板与这些未定义的函数不同。

有两个选项可以解决这个问题。

要么定义friend操作的类中,而不是仅仅宣布它有:

friend ostream& operator <<(ostream& out, CSet& other) { 
    // implementation 
} 

或者类定义之前声明函数模板:

template <class T> class CSet; 
template <class T> ostream& operator <<(ostream& out, CSet<T>&); 

,并宣布该模板是朋友:

friend ostream& operator << <T>(ostream& out, CSet&); 
          ^^^ 
+0

谢谢你的工作 – user4949421

相关问题