重载乘法运算符

时间:2015-04-15 00:32:27

标签: c++ operator-overloading multiplication

我正在为我的c ++课程做作业。我们不得不重载几个运算符,比如+, - ,!=,=等等。好吧,我除了乘法之外我都知道了。我尝试过的所有东西都会溢出或者只是编译。不知道我需要什么。

这是保存我的重载的头文件。

#ifndef COMPLEXNUMBER_H
#define COMPLEXNUMBER_H
#include<iostream>
using namespace std;

class ComplexNumber{
public:

    double real, imaginary;
    ComplexNumber(){
        real = 0;
        imaginary = 0;
    }
    ComplexNumber(double a, double b){
        real = a;
        imaginary = b;
    }
    ComplexNumber(double a){

        real = a;
        imaginary = 0;

    }

    ComplexNumber & operator= (const ComplexNumber & rhs){

        if(this == &rhs){

            return *this;

        }
        else{

            real = rhs.imaginary;
            imaginary = rhs.imaginary;
        }

        return *this;
    }

    ComplexNumber & operator+= (const ComplexNumber &rhs){

        real += rhs.real;
        imaginary += rhs.imaginary;
        return *this;

    }

    ComplexNumber & operator-= (const ComplexNumber &rhs){

        real -= rhs.real;
        imaginary -= rhs.imaginary;
        return *this;

    }

    const ComplexNumber operator+ (const ComplexNumber &rhs){

        ComplexNumber result = *this;
        result += rhs;
        return result;

    }

    const ComplexNumber operator- (const ComplexNumber &rhs){

        ComplexNumber result = *this;
        result -= rhs;
        return result;

    }

    const ComplexNumber operator* (const ComplexNumber &rhs){

        return *this * rhs;

    }

    friend ostream & operator<< (ostream &out, const ComplexNumber &c){

        out << "(" << c.real << (c.imaginary<0?" - ":" + ") << abs(c.imaginary) << " i)";
        return out;

    }

    friend istream & operator>> (istream & in, ComplexNumber &c){

        in >> c.real >> c.imaginary;
        return in;

    }

    operator double(){

        return real;

    }

    bool operator== (const ComplexNumber & rhs) const {

        bool result = (this->real == rhs.real) && (this->imaginary == rhs.imaginary);
        return result;

    }

    bool operator!= (const ComplexNumber &rhs) const{

        return !(*this == rhs);

    }
};

#endif

我知道乘法运算符是关闭的,但它正是我现在拥有的。这是它自己的。任何想法将不胜感激!!

const ComplexNumber operator* (const ComplexNumber &rhs){

            return *this * rhs;

        }

1 个答案:

答案 0 :(得分:1)

由于你调用它的方式,它会让你溢出。通过调用,您将复数乘以复数,并且只是在不做任何操作的情况下继续调用同一个运算符。您可以尝试使用一些基本数学并导出复数乘法的公式。具体来说,我们说我们有两个复数Z1和Z2。令Z1 = a + bi,其中a是实部,b是虚部,Z2 = c + di,其中c是实部,d是虚部。我们有Z1 * Z2 =(a + bi)(c + di)=(ac + adi + cbi-bd)。现在,我们将实部和虚部分开,这里的实部是没有i的一切,所以ac-bd,虚部是ad + cb。现在,在你的班级成员的条款中使用它,你会得到这样的东西:

const ComplexNumber operator* (const ComplexNumber &rhs)
{
    ComplexNumber result;
    result.real = real * rhs.real - imaginary * rhs.imaginary;
    result.imaginary = real * rhs.imaginary + imaginary * rhs.real;
    return result;
}
相关问题