我正在尝试在代码中重载运算符<<。如果我注释掉尝试在自定义类中使用 << 运算符的行,则它可以正常编译。该错误看起来几乎不像 C++ 库(?)。
我对这个问题的所有研究都表明这是一个链接问题。大多数人建议使用 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
知道是什么原因造成的吗?
最佳答案
我做了两项更改,一项是对好友定义的更改,一项是对原型(prototype)的更改。这应该编译:
#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;
}
这可以在 clang、g++ 和 ideone 中编译。
为了解释这个问题,编译器正在查看以下定义的链接时间:
std::ostream & operator<< <int>(std::ostream &, strange<int>&);
当您只有以下定义时:
std::ostream & operator<< <int>(std::ostream &, strange<int> const &);
这是因为您的原型(prototype)(显式原型(prototype)和 friend 原型(prototype))和您的定义之间存在沟通不畅。
关于c++ - 重载运算符<< c++;对 `std::basic_ostream 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12332082/