设计复数类Complex,实现运算符重载。

设计复数类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;
}


 

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值