在写一个类时,经常会重载操作符,下面就以一个例子来简单讲一下二元操作符重载。
什么是二元操作符呢? 比如a<b ,a+b, a-b等等诸如< ,+ ,- 的操作符。对其进行重载,有两种形式,一个是将其作为成员函数;另一个是将其作为友元函数。
#include <iostream>using namespace std;class Point{ int x; int y;public: Point(int a,int b) { x=a;
y=b; } bool operator < (Point& e) //重载二元操作符作为成员函数,注意参数只有一个,这里隐含了this { return (x <e.x && y <e.y); }};int main(){ Point abc(3,4);//要这样来调用构造函数初始化对象 Point def(5,6);//你原来写了小写的p if(abc <def) cout <<"I am less"; else cout <<"I am bigger"; cin.get(); return 0;}
#include <iostream>using namespace std;class Point{ int x; int y;public: Point(int a,int b) { x=a;y=b; } friend bool operator < (Point& p , Point& e) //友元函数进行重载,注意两个参数 { return (p.x <e.x && p. y <e.y); }};int main(){ Point abc(3,4);
Point def(5,6); if(abc <def) cout <<"I am less"; else cout <<"I am bigger"; cin.get(); return 0;}