本文介绍了C ++重载操作符<<在模板类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试重载运算子<<对于模板类,但我遇到错误...

I'm trying to overload operator<< for a template class but I'm getting errors...

最终(固定)代码:

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中引用

Error 1 error LNK2019: unresolved external symbol "public: __thiscall mytype::mytype(int)" (??0?$mytype@H@@QAE@H@Z) referenced in function _wmain

2)

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

Error 2 error LNK2019: unresolved external symbol "class std::basic_ostream > & __cdecl operator<<(class std::basic_ostream > &,class mytype const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$mytype@H@@@Z) referenced in function _wmain

3)

错误3 error LNK1120:2 unresolved externals

Error 3 error LNK1120: 2 unresolved externals

我的代码有什么问题?

推荐答案

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

You told the compiler to expect a free non-template function:

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

...但是您定义了一个函数模板:

...but then you defined a function template instead:

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

告诉编译器要等待一个函数模板:

Tell the compiler instead to expect a function template:

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

这篇关于C ++重载操作符&lt;&lt;在模板类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:23