帮朋友做的一笔试(友元 运算符重载)

12 篇文章 0 订阅
#include "stdafx.h"
#include <string.h>
/*
    题目:
    根据下列的类的定义,写出加法,乘法二元操作符的友元函数,
    而且每一个函数都应返回complex。
    并写入一个main函数来测试3+5i和6+2i的加和乘操作。
 */
#include<iostream.h>
class complex{
    double real,image;

   
public:
    complex(double r)
    {
        real=r;
        image=0;
    }
    void assign(double r,double i)
    {
        real=r;image=i;
    }
    void print(){cout<<real<<"+"<<image<<"i"<<endl;}
   
    friend complex operator + (const complex &x,const complex &y)
    {
        complex temp(0);
        temp.real= x.real + y.real;
        temp.image= x.image + y.image;
        return temp;
    }


    friend complex operator * (const complex &x,const complex &y)
    {
        complex temp(0);
        temp.real=x.real * y.real;
        temp.image=x.image*y.image;
        return temp;
    }
   
};



int main(int argc, char* argv[])
{
    complex ob1(3),ob2(6),ob3(0),ob4(0);

    ob1.assign(3,5);
    ob2.assign(6,2);

    cout<<"************************************"<<endl;
    ob1.print();
    ob2.print();
    cout<<"************************************"<<endl;
    //ob2=a+ob1;  //整型变量a与类complex对象ob1相加
    cout<<"(3+5i)+ (6+2i)= ";
    ob3=ob1+ob2;
    ob3.print();
    cout<<"************************************"<<endl;
    cout<<"(3+5i)*(6+2i)= ";
    ob4=ob1*ob2;  //整型变量a与类complex对象ob1相乘
    ob4.print();
}
 

注:关于构造函数是笔试中就是那样写的,主要是实现友元 运算符重载的那两个函数。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值