C++ Operator Overloading 运算符重载

index > C++ > Operator Overloading

有些事情好像理所当然,但是又不那么顺利。


构造器()

struct point {
    int x, y;
    point() {} // default constructor
    point (int _x, int _y) {
        x = _x; y = _y;
    }
};

也可以这样写:

struct point {
    int x, y;
    point() {} // default constructor
    point (int x, int y): x(x), y(y) {}
};

注* 括号里的是赋值的参数 好像容易记错。

小于号 <

struct point {
    int x, y;
    // overloading of < operator
    bool operator<(const point &rhs) const{
        // your main logic for the comparator goes here
        return make_pair(x,y) < make_pair(rhs.x, rhs.y);
    }
};

请要小心弱比较的特性(C++: Strict Weak Ordering),肯定有人疑惑过为什么只要定义一个小于号。因为对三种大小关系可以只用一个来实现,只不过等于的状态要比较两次,比如a<bb<a结果都为假,那么就判断为两者相等。

如果你在定义严格小的过程中,误用了等号,会导致难以预料的结果。而且很可能自己测试对了,某些样例过不了。

可以这样去理解:如果满足条件的时候,本身这个元素,一定放在另外一个元素之前,则这个条件要返还真。

可能有人会觉得) const {这个孤零零的很奇怪,但是这个是必要的语法结构。尤其是在被用于map或者优先队列之类key的时候。

<<

注* 必须要全局函数的形式(原理暂略)
reference

struct node {
    int x,y;
    friend ostream & operator << (ostream &out,node &T);
};
ostream & operator << (ostream &out,node &T){
    out<<T.x<<" "<<T.y;
    return out;
}

普通()

好像是有括号的计算是需要的(未证实)

struct node {
    int x,y;
    node operator ()(const node &T){return T;}
};

计算

struct node {
    int x,y;
    node ():x(0),y(0){}
    node (int x,int y):x(x),y(y){}
    int len(){return x*x+y*y;}
    node operator - (const node &T){return node(x-T.x,y-T.y);}
    node operator + (const node &T){return node(x+T.x,y+T.y);}
    int operator * (const node &T){return x*T.x+y*T.y;}
    int operator / (const node &T){return x*T.y-y*T.x;}//叉积
};

例题

一般都是在坐标运算,或者比较特殊的模拟的时候需要用到这些。
CodeForces - 136D :: Mine :: Dalao

参考

Using Constructors and comparison function in C++ By PraveenDhinwa

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值