简体   繁体   English

错误LNK2019:未解析的外部符号

[英]error LNK2019: unresolved external symbol

i have a template class, and when im runing the program it says 我有一个模板类,当我运行该程序时,它说

error LNK2019: unresolved external symbol "class std::basic_ostream > & __cdecl operator<<(class std::basic_ostream > &,class CSet &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$CSet@H@@@Z) referenced in function "public: void __thiscall Menu::menu(void)" (?menu@Menu@@QAEXXZ) 错误LNK2019:未解析的外部符号“class std :: basic_ostream>&__ cdecl operator <<(class 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)

on any kind of data structure i try to use, if anyone can explain to me why the overloading of printing function makes this error i'll be happy to ear about it. 在我试图使用的任何类型的数据结构,如果有人可以向我解释为什么打印功能的重载使这个错误我会很高兴听到它。

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;
}

The friend declaration does not declare a function template, but a separate function for each instantiation of the class template. friend声明不声明函数模板,而是为类模板的每个实例化声明一个单独的函数。 Therefore, the template you define is not the same as these functions, which remain undefined. 因此,您定义的模板与这些未定义的函数不同。

There are two options to fix this. 有两种方法可以解决这个问题。

Either define the friend operator inside the class, rather than just declaring it there: 在类中定义friend运算符,而不是仅在那里声明它:

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

Or declare the function template before the class definition: 或者在类定义之前声明函数模板:

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

and declare the template to be a friend: 并将模板声明为朋友:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM