模板类中的C++重载运算符<<

C++ overloading operator<< in a template class

本文关键字:lt 运算符 重载 C++      更新时间:2023-10-16

可能的重复项:
重载友元运算符<<用于模板类

我正在尝试重载运算符<<用于模板类,但我收到错误...


最终(固定)代码:

template<class T>
class mytype
{
    T atr;
public:
    mytype();
    mytype(T);
    mytype(mytype&);
    T getAtr() const;
    T& operator=(const T&);
    template<class U> friend ostream& operator<<(ostream&,const mytype<U>&);
};
template<class T>
mytype<T>::mytype()
{
    atr=0;
}
template<class T>
mytype<T>::mytype(T value)
{
    atr=value;
}
template<class T>
mytype<T>::mytype(mytype& obj)
{
    atr=obj.getAtr();
}

template<class T>
T mytype<T>::getAtr() const
{
    return atr;
}
template<class T>
T& mytype<T>::operator=(const T &other)
{
    atr=other.getAtr();
    return *this;
}
template<class U>
ostream& operator<<(ostream& out,const mytype<U> &obj)
{
    out<<obj.getAtr();
    return out;
}

(全部在头文件中)


VS2012 错误:

1)

错误

1 错误 LNK2019:未解析的外部符号"public: __thiscall mytype::mytype(int)"(??0?$mytype@H@@QAE@H@Z) 在函数 _wmain 中引用

2)

错误

2 错误 LNK2019:未解析的外部符号"class std::basic_ostream> & __cdecl 运算符<<(class std::basic_ostream> &,class mytype const &)"(??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$mytype@H@@@Z) 在函数_wmain中引用

3)

错误

3 错误 LNK1120:2 个未解析的外部


我的代码有什么问题?

你告诉编译器期待一个免费的非模板函数:

friend ostream& operator<<(ostream&,const mytype<T>&);

。但随后您定义了一个函数模板:

template<class T>
ostream& operator<<(ostream& out,const mytype<T> &obj)
{
    out<<obj.getAtr();
    return out;
}

告诉编译器需要函数模板:

template<class T> friend ostream& operator<<(ostream&,const mytype<T>&);

似乎缺少构造函数的实现/定义。

编辑 我现在看到问题已更新并且构造函数已定义。

在这种情况下,您只需要将构造函数定义放在标头中。有些人这样做的另一种方法是定义一个 .inl(inline) 文件并将其包含在标头的底部。

好吧,你声明构造函数

mytype(T);

但你从来没有真正去定义它。

编译器不会为上述构造函数创建默认主体,因为它不知道如何操作。

您还需要在类的运算符声明中指定template<class T>

template<class T>
class mytype
{
    T atr;
public:
    ...
    T getAtr() const;
    template<class U>
    friend ostream& operator<<(ostream&,const mytype<U>&);
    ...
};

或者,在类中实现运算符:

template<class T>
class mytype
{
    T atr;
public:
    ...
    T getAtr() const;
    friend ostream& operator<<(ostream&,const mytype<T>&)
    {
        ...
    }
    ...
};

至于第一个错误,可能是因为你在源文件中实现了mytype的构造函数。对于模板类,您应该在类中实现所有方法(和构造函数等)。