设计复数类Complex,实现运算符重载。 要求:
(1)重载运算符“+”和“*”,使之分别能用于复数相加和相乘。(30分)
(2)重载运算符“<<”,使得复数对象能够使用“<<”运算符输出。(15分)
实验思路:重载运算符要用到operator关键字,按照复数的计算方法重新定义运算符。
#include <iostream>
using namespace std;
class Complex{
public:
Complex(){} //默认构造函数
Complex (int arel,int aimag); //构造函数
Complex (const Complex &c); //复制构造函数
~ Complex (); //析构函数
Complex operator + (Complex &m); //重载 + 运算符
Complex operator * (Complex &m); //重载 * 运算符
friend ostream &operator << (ostream &out,
const Complex &m); //重载"<<"运算符
int getReal() const {return real;} //得到复数实部
int getImag() const {return imag;} //得到复数虚部
private:
int real,imag; //复数的实部与虚部
};
Complex::Complex (int areal,int aimag):real(areal),imag(aimag){}
Complex::Complex (const Complex &c):real(c.real),imag(c.imag){}
Complex::~Complex (){}
Complex Complex::operator + (Complex &m){
int a = this->real+m.real;
int b = this->imag+m.imag;
return Complex(a,b);
}
Complex Complex::operator * (Complex &m){
int a= this->real*m.real+this->imag*m.imag;
int b= this->imag*m.real+this->real*m.imag;
return Complex(a,b);
}
ostream &operator << (ostream &out,const Complex &m){
out << "(" << m.real << "," << m.imag << ")";
return out;
}
int main(){
Complex c1(5,4),c2(3,10),c3; //定义复数类的对象
c3 = c1 + c2;
cout << "c3" << c3;
Complex c4 = c1 * c2 ;
cout << "c4" << c4;
return 0;
}