结构体的构造与运算符重载

一:结构体的初始化与调用

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
在结构体作为容器元素的问题里,需要使用运算符重载来进行对数据比较判断

全部评论

相关推荐

求个付费实习岗位:这种就是吃满时代红利又没啥技术水平,只能靠压力学生彰显优越感的老登,别太在意了
点赞 评论 收藏
分享
程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务