簡體   English   中英

重載* =用於復數

[英]Overloading *= for complex numbers

我在使用重載運算符(* =)到目前為止難以確定與(ac-bd)+(ad + bc)相同的函數(a + bi)*(c + di)的算法時這是我的重載功能。 對於我對重載* =的定義,我不知道要寫什么來包含(ac-bd)的-bd部分。

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

class Complex {
public:
    Complex(double = 0, double = 0);
    void print() const { cout << real << '\t' << imag << '\n'; }
    // Overloaded +=
    Complex& operator +=(const Complex&);
    // Overloaded -=
    Complex& operator -=(const Complex&);
    // Overloaded *=
    Complex& operator *=(const Complex&);
    // Overloaded /=
    Complex& operator /=(const Complex&);
    double Re() const { return real; }
    double Im() const { return imag; }
private:
    double real, imag;
};

int main()
{
    Complex x, y(2), z(3, 4.5), a(1, 2), b(3, 4);
    x.print();
    y.print();
    z.print();
    y += z;
    y.print();
    a *= b;
    a.print();
    return 0;
}

Complex::Complex(double reel, double imaginary)
{
    real = reel;
    imag = imaginary;
}

// Return types that matches the one in the prototype = &Complex
Complex& Complex::operator+=(const Complex& z)
{
    real += z.Re();
    imag += z.Im();
    //How to get an object to refer to itself
    return *this;
}
Complex& Complex::operator *= (const Complex& z)
{
    real *= (z.Re());
    imag *= z.Re();
    return *this;
}

您可以使用std::tiestd::make_tuple執行多個分配:

std::tie(real, imag) = std::make_tuple(real*z.real - imag*z.imag,
                                       real*z.imag + imag*z.real);
return *this;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM