重载函数在类外

来源:互联网 发布:阿尔德里奇身体数据 编辑:程序博客网 时间:2024/06/05 11:56

二.重载符号的函数既不是友元又不是成员,怎么办呢?

 

定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。将运算符函数重载为非成员、非友元的普通函数。编写程序,求两个复数之和。

Input

两个复数

Output

复数之和

Sample Input

3 4

5 -10

Sample Output

(8.00,-6.00i)



 

#include <iostream>#include <iomanip>using namespace std;class Complex{public:    Complex();//无参构造函数    Complex(double r,double i);//有参构造函数//有构造函数就必有初始化,不在类内就在类外,一定要有这个意识!    double get_real();    double get_imag();//用了两个函数    void display();private:    double real;    double imag;};Complex::Complex(){real=0;imag=0;}Complex::Complex(double r,double i){real=r;imag=i;}//初始化,这个带参的初始化要训练自己用参数表的形式【Complex::Complex(double r,double i):real(r),imag(i){}】,不要写错了,并且牢记位置double Complex::get_real(){    return real;}double Complex::get_imag(){    return imag;}Complex operator +(Complex&c1,Complex&c2){    Complex temp(c1.get_real()+c2.get_real(),c1.get_imag()+c2.get_imag());    return temp;}//注意两点:一:函数类型是Complex;第二:函数名叫做“operator +”;在这个函数里调用了基类中的两个函数。void Complex::display(){    cout<<"("<<real<<","<<imag<<"i)"<<endl;}int main(){    double real,imag;    cin>>real>>imag;    Complex c1(real,imag);    cin>>real>>imag;    Complex c2(real,imag);    Complex c3=c1+c2;    cout<<setiosflags(ios::fixed);    cout<<setprecision(2);    c3.display();    return 0;}


 

0 0
原创粉丝点击