⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 例10.7.txt

📁 谭浩强C++PPT课件
💻 TXT
字号:
例10.7 在例10.2的基础上,用重载的“<<”输出复数。 
#include <iostream>
using namespace std; 
class Complex
{public:
Complex( ){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator + (Complex &c2);                    //运算符“+”重载为成员函数
friend ostream& operator << (ostream&,Complex&);     //运算符“<<”重载为友元函数
private:
double real;
double imag;
};

Complex Complex∷operator + (Complex &c2)               //定义运算符“+”重载函数
{return Complex(real+c2.real,imag+c2.imag);}
ostream& operator << (ostream& output,Complex& c)       //定义运算符“<<”重载函数
{output<<″(″<<c.real<<″+″<<c.imag<<″i)″<<endl;
return output;
}

int main( )
{Complex c1(2,4),c2(6,10),c3;
c3=c1+c2;
cout<<c3;
return 0;
}
(在Visual C++ 6.0环境下运行时,需将第一行改为#include <iostream.h>,并删去第2行。)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -