我想在我的代码中超载运算符< <。如果我注释掉我尝试在我的自定义类中使用<运算符的行,它编译得很好。该错误几乎看起来像它不喜欢C++库(?)。重载运算符<< C++;未定义的参考`std :: basic_ostream
我对这个问题的所有研究都表明它是一个链接问题。大多数人建议使用g ++而不是gcc。我正在使用g ++作为我的编译器,并且仍然出现此错误。
代码:
#include <iostream>
using namespace std;
//prototype the class and the functions
template<class T> class strange;
template<class T> ostream& operator<< (ostream& osObject, strange<T>& sObject);
//begin class
template <class T>
class strange
{
public:
// .... function prototypes go here.
strange(T x,T y);
friend ostream& operator<< <> (ostream& osObject, strange<T>& sObject);
private:
T a;
T b;
};
// .... your function definitions go here
template <class T>
strange<T>::strange(T first, T second){
a = first;
b = second;
}
template <class T>
ostream& operator<< (ostream& osObject, const strange<T>& sObject){
osObject << sObject.a << ", " << sObject.b;
return osObject;
}
int main()
{
strange<int> x1(4,6) , x2(12,2) ;
//strange<char> y1('m','n') , y2('m','n') ;
cout << "x1 = " << x1 << endl;
return 0;
}
错误:
test.cpp:(.text+0x7a): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& operator<< <int>(std::basic_ostream<char, std::char_traits<char> >&, strange<int>&)'
collect2: ld returned 1 exit status
任何想法是什么原因造成的?
难道你的操作符定义是在'.cpp'文件中,而不是在头部? – juanchopanza
不会 '#包括;' 和 'using namespace std;' 照顾(ostream&)? –
Jeff
不,您的*模板代码必须通过包含来访问。 – juanchopanza