gpt4 book ai didi

c++ - 重载运算符<< c++;对 `std::basic_ostream 的 undefined reference

转载 作者:搜寻专家 更新时间:2023-10-31 01:13:36 25 4
gpt4 key购买 nike

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

知道是什么原因造成的吗?

最佳答案

我做了两处更改,一处是 friend 定义,一处是原型(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)和友元)与您的定义之间的沟通不畅。

关于c++ - 重载运算符<< c++;对 `std::basic_ostream 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12332082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com