#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class B
{
int val;
public:
B(int v):val(v){}
int getV() const {return val;}
bool operator < (const B & v)const {return val<v.val;}
};
ostream & operator <<(ostream & out, const B& v)
{
out<<v.getV();
return out;
}
template<class T> struct Out
{
ostream & out;
Out(ostream & o): out(o){}
void operator()(const T& val){out<<val<<" ";}
};
int main() {
B t1[]={3,2,4,1,5};
B t2[]={5,6,8,2,1};
vector<B> v1(10,0);
sort(t1,t1+5);
sort(t2,t2+5);
set_union(t1,t1+5,t2,t2+5,v1.begin());
for_each(v1.begin(),v1.end(), Out<B>(cout)); cout<<endl;
return 0;
}
Hello, I have question about this code.
For now, I study for C++ certification and I study with the study guide book now.
In many questions on the book, I often see the code that
class B
{
int val;
public:
B(int v):val(v){}
int getV() const {return val;}
bool operator < (const B & v)const {return val<v.val;}
};
ostream & operator <<(ostream & out, const B& v)
{
out<<v.getV();
return out;
}
template<class T> struct Out
{
ostream & out;
Out(ostream & o): out(o){}
void operator()(const T& val){out<<val<<" ";}
};
I have tried to understand this part but I actually confused how these work, so I would like someone to explain what these codes do.
I really appreciate that if someone answer this question.
Thank you.
question from:
https://stackoverflow.com/questions/66057486/operator-overloading-and-ostream-in-the-class 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…