C++语言程序设计

下面的实例是一个复数类的说明：

| 程序12-11

class complex
{
private:
double a;
double b;
public:
complex();
complex(double i, double j);
complex operator +(complex& x);
complex operator -(complex& x);
complex operator *( complex& x);
complex operator /( complex& x);
void setreal(double x);
void setimag(double y);
double getreal();
double getimag();
friend ostream& operator <<(ostream& Out,complex& x);
friend istream& operator>>(istream& In, complex& x);
};

在这里，重载的插入和抽取运算符被定义成复数类的友元，通过定义友元函数，可以访问该类的私有成员。下面是它们的实现：

| 程序12-12

ostream& operator<<(ostream& Out, complex& x)
{
Out<<x.a<<"+j"<<x.b;
return Out;
}

istream& operator>>(istream& In, complex& x)
{
In>>x.a>>x.b;
return In;
}

复数类的其它成员函数的实现略去，下面是应用复数类的例子：

| 程序12-13

void main()
{
complex a,b,c;
cin>>a>>b;
c=a+b;
cout<<c;
}

输入2 3 4 5，程序运行结果为：
6+j8