模板类中的C++重载运算符<<
C++ overloading operator<< in a template class
可能的重复项:
重载友元运算符<<用于模板类
我正在尝试重载运算符<<用于模板类,但我收到错误...
最终(固定)代码:
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的构造函数。对于模板类,您应该在类中实现所有方法(和构造函数等)。
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- C++ostream:没有运算符匹配<<&应在'&'代币
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 当运算符<存在时,为什么要定义 LT?
- log4cxx访问异常,使用<<运算符和宏
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多