请教一下C++ STL set问题,模板类,重载<<输出

2025-01-05 06:13:00
推荐回答(3个)
回答1:

友元函数是一个模板函数,声明的时候要加上template
成员函数有this指针,而友元函数没有this指针。所以类声明中的T对成员函数是可见的,对友元函数不可见。

回答2:

吓尿, 没初始化set就直接输出. 哪抄来的代码.
帮你修正了代码的错误, 重载没问题

#include
#include
using namespace std ;
template class Edge
{
private:
int v1;
int v2;
T data;
public:
template
friend ostream& operator << (ostream& os,const Edge& edge)
{
os << edge.v1 << " " << edge.v2 << " " << edge.data;
return os;
}
Edge(int v1,int v2,T data)
{
this->data = data;
this->v1 = v1;
this->v2 = v2;
}
T getData()
{
return this->data;
}
};
template
struct strLess
{
bool operator() (Edge e1, Edge e2)
{
return (e1.getData()-e2.getData())<0;
}
};
int main()
{
Edge< int > e( 0, 0, 1 ) ;
Edge< int> e1( 0, 0, 2 ) ;
Edge e2( 0, 0, 3 ) ;
set ,strLess> s;
s.insert( e ) ;
s. insert( e2 ) ;
s. insert( e1 ) ;
set,strLess>::iterator iter;
for (iter=s.begin();iter!=s.end();iter++)
{
cout << *iter << " " << endl ;;
}
return 0;
}

回答3:

基本的模板语法很多地方都有问题,基本的东西都没弄清楚,基础不扎实啊,

#include
#include
using namespace std;
template
class Edge
{
public:
template
friend ostream& operator << (ostream&, const Edge&);
Edge(int v1,int v2,T data)
{
this->data = data;
this->v1 = v1;
this->v2 = v2;
}
T getData()
{
return this->data;
}
private:
int v1;
int v2;
T data;
};

template
ostream& operator << (ostream &os, const Edge &edge)
{
os << edge.v1 << " " << edge.v2 << " " << edge.data;
return os;
}

template
struct strLess : public binary_function< Edge, Edge, bool>
{
bool operator() (const Edge& e1, const Edge& e2) const
{
return (e1.getData()-e2.getData())<0;
}
};

int main()
{
set , strLess > s;
set< Edge, strLess >::iterator iter;
for (iter=s.begin();iter!=s.end();iter++)
{
cout << *iter << " ";
}
return 0;
}