#include<iostream>
using namespace std;
class Complex{
private://类内初始化
<span style="white-space:pre"> </span>double real=0;
<span style="white-space:pre"> </span>double image=0;
public:
<span style="white-space:pre"> </span>Complex() = default;//当存在构造函数时,系统不会合成默认构造函数这将导致无法完成类内初始化,除非显示调用Complex() = default;
<span style="white-space:pre"> </span>Complex(double r, double i) :real(r), image(i){}//类内定义将默认为inline
<span style="white-space:pre"> </span>Complex(double d){ real = d; image = 0; }//转换构造函数
<span style="white-space:pre"> </span>//friend Complex operator+(Complex&, Complex&);引用实际上是传址,所以当其中一个参数非complex类型时,就无法调用转换构造函数
<span style="white-space:pre"> </span>friend ostream& operator<<(ostream&, Complex&);//将返回的引用作为左值
<span style="white-space:pre"> </span>friend Complex operator+(Complex, Complex);//双目运数符应声明为友元
<span style="white-space:pre"> </span>/*operator double(){ return real; }类型转换函数,complex型转成double。c = c1 + 2.5中,当类型转换函数与转换构造函数同时存在会导致二义
<span style="white-space:pre"> </span>性:是double+double;还是complex+complex?*/
<span style="white-space:pre"> </span>//类型转换函数和转换构造函数有共同特点:当运行过程中需要它时编绎系统会自动调用,建立临时对象或变量
};
#include"complex.h"
Complex operator+(Complex c1, Complex c2){
<span style="white-space:pre"> </span>return Complex(c1.real + c2.real, c1.image + c2.image);
}
ostream& operator<<(ostream& output, Complex& c ){
<span style="white-space:pre"> </span>output << "(" << c.real << "," << c.image << ")" << endl;
<span style="white-space:pre"> </span>return output;
}
#include"complex.h"
inline void show(Complex& c){ cout << c; }
int main(){
Complex c1(1, 2), c2(3, 4), c;
c = c1 + c2;
show(c);
c = c1 + 2.5;
show(c);
return 0;
}
对于运算符"+"的重载有些人会这么做:"complex operator+(complex )",那么"c1+c2<=>c1.operator+(c2),"这样"c1+2.5可以运行,但2.5+c1却不行",这是不符合加法交
换律的.所以对于双目运算符应如此说明:"friend Complex operator+(Complex, Complex)"<span style="font-family:Arial, Helvetica, sans-serif;"><span style="white-space: normal;">
</span></span>