操作符重载
一、要重载操作符,需使用被称为操作符函数的特殊函数形式。操作符函数的格式如下:
operator op(argument-list)其中,op是将要被重载的操作符,op必须是有效的c++操作符,不能虚构一个新的符号。
total=coding+fixing(重载+)注意:操作符左侧的对象是调用对象,操作符右边的对象是作为参数被传递的对象。
二、c++对用户定义的操作符重载的限制:
1.重载后的操作符必须至少有一个操作数是用户定义的类型。
2.使用操作符时不能违反操作符原来的句法规则。比如“+”不能重载成有三个操作数。同样不能修改操作符的优先级
3.不能定义新的操作符。
三、友元函数
创建友元函数的第一步是将其原型放在类声明中,并在原型声明前加上关键字friend。不能使用成员操作符来调用友元函数,友元函数的访问权限与成员函数相同。在定义中不要使用friend。
注意:friend声明紧跟在类名之后,而不是放在public、private或protected中,因为友元不是授权类的成员,并且该关键字只能出现在类中。
举例:
class String
{
friend bool operator==(const String&,const String&);
friend bool operator==(const String&,const char*);
public:
//……..
private:
//………
}
class B;
class A
{
friend class B;
public:
//…….
Private:
//……
}
class A
{
friend class B;
public:
//…….
Private:
//……
}
通过上述声明,B可以访问A的所有私有成员,不过A不一定可以访问B的,除非在B类中声明A为友元。
四、成员函数还是非成员函数
对于成员函数版本来说,一个操作数通过this指针隐式地传递,另一个操作数作为函数参数显式地传递;对于友元函数来说,两个操作数都作为参数来传递。
Time operator+(const Time& t)const friend Time operator+(const Time& t1,const Time& t2)
记住,在定义操作符时,必须选择其中的一种格式,而不能同时选择这两种格式。因为这两种格式都与同一个表达式匹配,同时定义这两种格式将被视为二义性错误,导致编译错误。
我们分别用两种实现方式写point类的”+“和”-“的重载,来表现两种方式的不同。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 View Code 2 #include <iostream> 3 4 using std::endl; 5 using std::cout; 6 7 class point 8 { 9 double x; 10 double y; 11 public: 12 double get_x() 13 { 14 return x; 15 } 16 double get_y() 17 { 18 return y; 19 } 20 point(double X = 0.0 , double Y = 0.0):x(X),y(Y){}; 21 friend point operator -(point p1,point p2); 22 point operator +(point p); 23 }; 24 //重载操作符“-” 25 point operator -(point p1,point p2) 26 { 27 double x = p1.get_x() - p2.get_x(); 28 double y = p1.get_y() - p2.get_y(); 29 point p3(x,y); 30 return p3; 31 } 32 //重载操作符“+” 33 point point::operator +(point p) 34 { 35 double x = this->x + p.x; 36 double y = this->y + p.y; 37 point tmp_p(x,y); 38 return tmp_p; 39 } 40 int main() 41 { 42 point p1(1.2,3.2); 43 point p2(1.1,3.1); 44 point p3 = p1+p2; 45 point p4 = operator-(p1,p2); 46 cout<<p3.get_x()<<" "<<p3.get_y()<<endl; 47 cout<<p4.get_x()<<" "<<p4.get_y()<<endl; 48 return 0; 49 }