gpt4 book ai didi

c++ - 重载 *= 用于复数

转载 作者:行者123 更新时间:2023-11-27 23:59:09 25 4
gpt4 key购买 nike

我无法理解函数 (a+bi)*(c+di) 的算术运算,它与 (ac-bd) + (ad+bc) 具有重载运算符 ( *= )到目前为止,我有这个用于我的重载功能。对于我对重载 *= 的定义,我不知道要写什么来包含 (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;

关于c++ - 重载 *= 用于复数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40432765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com