定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。
代码为:
#include <iostream> //用VC++时改为∶ #include <iostream.h>
using namespace std; //用VC++时为取消此行
class Complex
{public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator+(Complex &c2);
Complex operator+(int &i);
friend Complex operator+(int&,Complex &);
void display();
private:
double real;
double imag;
};
Complex Complex::operator+(Complex &c)
{return Complex(real+c.real,imag+c.imag);}
Complex Complex::operator+(int &i)
{return Complex(real+i,imag);}
void Complex::display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}
Complex operator+(int &i,Complex &c)
{return Complex(i+c.real,c.imag);}
int main()
{Complex c1(3,4),c2(5,-10),c3;
int i=5;
c3=c1+c2;
cout<<"c1+c2=";
c3.display();
c3=i+c1;
cout<<"i+c1=";
c3.display();
c3=c1+i;
cout<<"c1+i=";
c3.display();
return 0;
}
扩展资料:
注意事项
可以用下列结构描述复数信息;
struct complex
{
int real;
int image;
};
试写出两个通用函数,分别用来求两复数的和与积。其函数原型分别为:
struct complex add(struct complex c1,struct complex c2);
即参数和返回值用结构变量。
输入:
推荐于2017-11-22
#include<iostream>
using namespace std;
class Complex{
public:
int real, //实数部分
virt;//虚数部分
Complex& operator+(Complex& com){
Complex temp;
temp.real = this->real + com.real;
temp.virt = this->virt + com.virt;
return temp;
}
};
int main(){
Complex com1, com2, com3;
cin >> com1.real >> com1.virt;
cin >> com2.real >> com2.virt;
com3 = com1 + com2;
cout << com3.real <<" "<< com3.virt << endl;
system("pause");
}
类的重载运算符
#include<iostream>
using namespace std;
class Complex{
public:
int real, //实数部分
virt;//虚数部分
};
Complex& operator+(Complex& com1, Complex &com2){
Complex temp;
temp.real = com1.real + com2.real;
temp.virt = com1.virt + com2.virt;
return temp;
}
int main(){
Complex com1, com2, com3;
cin >> com1.real >> com1.virt;
cin >> com2.real >> com2.virt;
com3 = com1 + com2;
cout << com3.real <<" "<< com3.virt << endl;
system("pause");
}
将运算符重载为普通函数