c++中重载运算符

重载运算符

1,成员函数运算符

运算符重载为类的成员函数一般格式如下

<函数类型> operator <运算符> (参数表)

{函数体}

调用成员函数运算符如下

<对象名>. operator <运算符>(参数)

2.友元函数运算符

一般格式:friend <函数类型> operator <运算符> (参数表)

{函数体}

当运算符为类的友元函数时,没有隐含的this指针,通过函数的形参进行传递函数的参数和操作类

一般情况下,单目运算符最好重载为类的成员函数, 双目运算符则最好重载为类的友元函数,=, () , [] , -> 不能重载为类的友元函数。

3重载前置运算符

成员运算符函数形式:ob.operator ++()

友元函数运算符形式:operator ++ (类名 & obj)

重载后置运算符

成员运算符函数形式:ob .operator ++(int)

友元运算符函数形式:operator ++(类名 &  obj , int)

(用是否在参数列表中有关键字int,来区分前置还是后置)

4.插入运算符和析取运算符的重载

1)插入运算符重载

对运算符<< 进行重载,能够输出各种标准类型的数据,其原型如下

ostream & operator << (ostream & ,类名 & 对象)

2)析取运算符重载

对运算符>>进行重载,能输出各种类型的数据,其原型如下

istream & operator << (istream &,类名 & 对象)

小结

双目运算符重载为类的成员函数时,函数只显示说明一个参数,该参数是运算符的右操作数

前置单目运算符重载为类的成员函数时,不需要显示说明参数,即函数没有形参。

后置单目运算符重载为类的成员函数时,函数要有一个整形实参。

规则

五个不能重载的运算符 .  .*  ::  sizeof  ?:

重载不能改变运算符运算对象的个数

重载不能改变运算符的优先级

重载不能改变运算符的结合性

重载运算符的函数不能有默认参数

重载的的运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应该有一个是类对象或类对象的应用。

写了一个小例子如下

例子如下

1 #include<iostream>                                                     
 2 #include<string>
 3 #include<iomanip>
 4 
 5 using namespace std;
 6 
 7 class Complex
 8 {
 9     public:
10         Complex(){
11             real=0; img=0;
12         }
13         Complex(double r , double i){real = r; img = i;}
14         Complex operator + (Complex &c1);
15         Complex operator - (Complex &c1);
16         void display();
17 
18     private:
19         double real;
20         double img;
21 
22 };
23 
24 Complex Complex :: operator + (Complex &c1)
25 {
26     Complex c;
27     c.real = real + c1.real;
28     c.img = img + c1.img;
29     return c;
30 }
31 
32 Complex Complex :: operator - (Complex &c1)
33 {
34     Complex c;
35     c.real = real - c1.real;
36     c.img = img - c1.img;
37     return c;
38 }
39 
40 void Complex :: display()
41 {
42     cout << "("<< real << ", "<< img << "i)" << endl;
43 }
44 
45 int main(int argc , char **argv)
46 {
47     Complex c(3,4) , c1(2,5) ,c2 , c3;
48     c2 = c + c1;
49     c3 = c - c1;
50     cout << "c+c1=";
51     c2.display();
52     cout << "c-c1=";
53     c3.display();
54     return 0;
55 }
原文地址:https://www.cnblogs.com/tanshengjiang/p/11857091.html