链式操作

链式操作是利用运算符进行连续操作。它的特点是一条语句中出现两个或两个以上相同的操作符。

1、操作符重载函数一定不能够返回void类型。

2、对赋值操作符进行重载,如果返回的是类的对象,那么链式赋值操作必须借助拷贝构造函数才能进行。这样不但会有较大的运行开销,还需要编写正确的拷贝构造函数。

 1 #include<iostream>
 2 using namespace std;
 3 class Complex{
 4     double real;
 5     double image;
 6 public:
 7     Complex(double r =0.0,double i=0.0){
 8         real =r ;
 9         image = i;
10     }
11     Complex(const Complex &c){
12         cout<<"Copy Constructor"<<endl;
13         real = c.real;
14         image = c.image;
15     }
16     void show(){
17         cout<<real<<"+"<<image<<"i"<<endl;
18     }
19     Complex operator=(const Complex &);
20 };
21 
22 Complex Complex::operator=(const Complex &c){
23     real = c.real;
24     image = c.image;
25     return c;
26 }
27 int main(){
28     Complex c1(2.3,4.5),c2,c3;
29     c1.show();
30     c3=c2=c1;
31     c2.show();
32     c3.show();
33     return 0;
34 }
35 输出:
36 2.3+4.5i
37 Copy Constructor
38 Copy Constructor
39 2.3+4.5i
40 2.3+4.5i

c3=c2=c1会出现两次临时对象,所以要进行两次拷贝构造函数。

posted @ 2016-10-25 15:02  IT男汉  阅读(430)  评论(0编辑  收藏  举报