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

error LNK2019: unresolved external symbol

本文关键字:外部 符号 LNK2019 错误      更新时间:2023-10-16

我有一个模板类,当我运行程序时它说

错误LNK2019:未解析的外部符号"类std::basic_ostream> &__cdecl operator<<(类std::basic_ostream> &,类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)

在我尝试使用的任何数据结构上,如果有人能告诉我为什么打印函数重载会导致这个错误,我会很高兴听到的。

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

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&);
                            ^^^