`
xusaomaiss
  • 浏览: 608822 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

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

 
阅读更多
#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();
}
 

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

分享到:
评论
1 楼 无心流泪wan 2013-10-04  
乘法法则
规定复数的乘法按照以下的法则进行:
设z1=a+bi,z2=c+di(a、b、c、d∈R)是任意两个复数,那么它们的积(a+bi)(c+di)=(ac-bd)+(bc+ad)i.
其实就是把两个复数相乘,类似两个多项式相乘,展开得: ac+adi+bci+bdi^2,因为i^2=-1,所以结果是(ac-bd)+(bc+ad)i 。两个复数的积仍然是一个复数。

相关推荐

Global site tag (gtag.js) - Google Analytics