结构体的构造与运算符重载
一:结构体的初始化与调用
struct node1//初始化
{
int a,b;
mode1(int a,int b)
{
this->a=a;
this->b=b;
}
};
int main()
{
node1 temp1;
//temp1.a=1;
//temp1.b=2;
cout<<temp1.a<<temp1.b<<endl
}结构体内的数据额可以通过这样来初始化
包括字符串,数字,字符等......
二:改变构造方法与容器搭配
struct node2//改变构造方法
{
node(){}
string a;int b;
node2(string ss,int len)
{
a=ss;
b=len;
}
};
int main()
{
string str="111 *";
queue<node2> q;
q.push(node2(str,0));
cout<<q.front().a<<q.front().b<<endl;
}可以改变容器里的结构体的表示方法
可以更快捷的完成对数据的操作
三:结构体里的运算符重载
struct node3//运算符重载
{
int a,b;
bool operator == (const node3 c) const
{
return c.a==c.b+1;
}
};
int main()
{
node3 temp[10];
temp[0].b=1;temp[0].a=1;
temp[2].b=1;temp[2].a=2;
if(temp[0]==temp[0])printf("wow\n");
else if(temp[2]==temp[2])printf("yes\n");
}
输出结果为yes
在结构体作为容器元素的问题里,需要使用运算符重载来进行对数据比较判断

查看14道真题和解析
