C++重载运算符及const成员函数简述

ACM中,用重载函数会使解题更加方便,但是又需要像c++那样深入理解,遂简单总结了结构体中的重载运算符及const成员函数一些简单的用法.

闲言少叙,直接看代码:

/**
  * 行有余力,则来刷题!
  * 博客链接:http://blog.csdn.net/hurmishine
  *
*/
#include <iostream>
#include <cstdio>
#include <set>
using namespace std;
const int maxn=0;
struct Node
{
    int x,y;
    Node()
    {
        x=0,y=0;
    }
    Node(int x,int y):x(x),y(y) {}

    void setX(int x)
    {
        this->x=x;
    }
    //普通对象成员函数
    void print()
    {
        cout<<"("<<x<<","<<y<<")"<<endl;
    }
    //常对象成员函数
    void print()const
    {
        cout<<"const"<<"("<<x<<","<<y<<")"<<endl;
    }
    //重载小于运算符,(set)
    friend bool operator<(Node n1,Node n2)
    {
        //注意逻辑
        if(n1.x==n2.x)
        {
            return n1.y<n2.y;
        }
        return n1.x<n2.x;
    }
    //重载<<运算符
    friend  ostream & operator << (ostream &os, Node node)
    {
        cout << "(" <<node.x<<","<<node.y<< ")";
        return os;
    }
};
int main()
{
    Node n1;//默认构造函数
    //cout<<n1<<endl;
    Node n2(1,2);
    //n2.print();
    //n2.setX(2);
    //n2.print();
    //cout<<n2<<endl;
    const Node n3(2,2);
    //n3.print();
    //cout<<n3<<endl;
    //n3.setX(2);//ERROR

    Node const n4(3,3);
    //cout<<n4<<endl;
    //n4.setX(2);//ERROR
    //cout<<"-----------"<<endl;

    set<Node>s;
    s.insert(n1);
    s.insert(n2);
    s.insert(n3);
    s.insert(n4);
    s.insert(Node(4,2));
    s.insert(Node{-1,1});//如果未写构造函数
    set<Node>::iterator it;
    for(it=s.begin(); it!=s.end(); it++)
    {
        cout<<*it<<endl;//重载了<<运算符
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值