【发布时间】:2012-11-14 06:33:30
【问题描述】:
我正在尝试为模板类重载运算符
最终(固定)代码:
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:函数 _wmain 中引用的未解析外部符号“public: __thiscall mytype::mytype(int)”(??0?$mytype@H@@QAE@H@Z)
2)
错误 2 错误 LNK2019:无法解析的外部符号“class std::basic_ostream > & __cdecl operator &,class mytype const &)” (??6@YAAAV?$basic_ostream@DU? $char_traits@D@std@@@std@@AAV01@ABV?$mytype@H@@@Z) 在函数_wmain中引用
3)
错误 3 error LNK1120: 2 unresolved externals
我的代码有什么问题?
【问题讨论】:
-
不,Visual Studio 在 C++ 控制台应用程序中使用 _tmain 而不是 main
-
每个 C++ 程序都需要有一个
main函数作为入口点。您尝试在 Windows 中执行此操作的事实与您遇到的问题是正交的。 -
@JohnDibling,所以你的评论在这里毫无意义,因为它根本与问题无关。
-
我不是 VS 专家,因为我在 linux 下工作,但我也知道 VS 使用 _tmain,因此本身不需要 main(),我不需要认为这是问题
-
使用 Windows 特定的
_tmain函数而不是标准规定的main函数会稍微混淆问题。不是每个人都熟悉 Windows,但假定 [C++] 标记中的每个人都在谈论标准 C++。您可能会对此处的特定于 Windows 的构造感到悲伤,这可能会妨碍获得实际答案。如果您遇到的问题并非特定于 Windows,我建议您将代码更改为使用标准构造。
标签: c++ class templates operator-overloading