c++中,类中自身类对象不能做自己的类成员,但可以做静态数据成员,引用数据成员,以及vector,set中的类型成员。
如下面代码中定义的类。
#include<iostream>
#include<set>
using namespace std;
class A{
public:
int a,b,c;
set<A> subA;
A(){};
A(int aa,int bb,int cc){
a = aa;
b = bb;
c = cc;
}
A(int aa,int bb,int cc,set<A> dd){
a = aa;
b = bb;
c = cc;
subA = dd;
}
};
int main(){
A aa(1,2,3);
A bb(1,3,3);
int b = 1;
set<A> sub1,sub2;//(aa,bb);
sub1.insert(aa);
sub2.insert(bb);
A dd(4,5,6,sub1);
A ee(4,5,6,sub2);
set<A> ff;
ff.insert(ee);
ff.insert(dd);
cout<<dd.a<<dd.b<<dd.c<<endl;
}
如上面代码,class A中定义了自身类型的set,但set需要有自身的比较函数。同时细想之后会发现,对A的比较还需要递归调用比较函数,因此只能使用博客
https://blog.csdn.net/xll_bit/article/details/101302124
中对操作符<重载的方法。
改进后的类代码如下,注意 < 操作符的循环调用。(代码测试通过)
#include<iostream>
#include<set>
using namespace std;
class A{
public:
int a,b,c;
set<A> subA;
A(){};
A(int aa,int bb,int cc){
a = aa;
b = bb;
c = cc;
}
A(int aa,int bb,int cc,set<A> dd){
a = aa;
b = bb;
c = cc;
subA = dd;
}
bool operator< (const A &other) const {
if((a == other.a) && (b == other.b) && (c == other.c) && (subA.size() == other.subA.size())){
if(subA.size() == 0)
return false;
else {
set<A>::iterator iter1,iter2;
for(iter1 = subA.begin(),iter2 = other.subA.begin();iter1 != subA.end();iter1 ++,iter2 ++)
return *iter1 < *iter2;
}
}
else {
if( a != other.a)
return a < other.a;
else if(b != other.b)
return b < other.b;
else if(c != other.c)
return c < other.c;
else
return subA.size() < other.subA.size();
}
}
};
另有高性能,深度学习,人工智能培训,报名咨询 优惠等着你!