2012-09-08 194 views
2

我想在我的代码中超载运算符< <。如果我注释掉我尝试在我的自定义类中使用<运算符的行,它编译得很好。该错误几乎看起来像它不喜欢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 

任何想法是什么原因造成的?

+1

难道你的操作符定义是在'.cpp'文件中,而不是在头部? – juanchopanza

+0

不会 '#包括;' 和 'using namespace std;' 照顾(ostream&)? – Jeff

+0

不,您的*模板代码必须通过包含来访问。 – juanchopanza

回答

4

我做了两个改变,一个是朋友定义,另一个是原型。这应该编译:

#include <iostream> 
using namespace std; 

//prototype the class and the functions 
template<class T> class strange; 
template<class T> ostream& operator<< (ostream& osObject, const 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, const 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; 
} 

这将编译铛,g ++以及在ideone

为了说明问题,编译器正在寻找在链接时的定义:

std::ostream & operator<< <int>(std::ostream &, strange<int>&); 

当你只有一个定义:

std::ostream & operator<< <int>(std::ostream &, strange<int> const &); 

这是因为m你的原型(明确的和朋友)和你的定义之间的沟通。

+0

立即尝试......“在课堂以外使用的朋友” – Jeff

+0

我指的是第16行。 –

+0

奇怪。用clang编译,而不用g ++。再给我几分钟。 –

相关问题