重载乘法运算符

Overloading Multiplication Operator

本文关键字:运算符 重载      更新时间:2023-10-16

我正在为我的 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;
        }

由于您调用它的方式,它为您提供溢出。通过您的呼叫,您将复数乘以复数,而它只是不做任何事情而一直呼叫同一个接线员。您可以尝试使用一些基本的数学运算并导出复数乘法的公式。具体来说,假设我们有两个复数 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;
}