重载*=用于复数
Overloading *= for complex numbers
我遇到了麻烦,得到的算术函数(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::tie
和std::make_tuple
执行多个赋值:
std::tie(real, imag) = std::make_tuple(real*z.real - imag*z.imag,
real*z.imag + imag*z.real);
return *this;
相关文章:
- 重载操作程序时出错>>用于类中的字符串 memebr
- 重载==不适用于二进制树
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 如何调用用于重载运算符"<<"的 friend 函数?
- 重载 std::字符串运算符+ 用于打印枚举名称
- 一种优雅或至少可行的方法,用于使用和接受具有重载方法和运算符的不同大小的文字数组常量
- 重载运算符 += 用于 C++ 中的链表
- 隐式生成的函数重载用于右值参数?
- 重载运算符 + 用于向量:命名空间标准
- 重载运算符 [] 用于从对象数组中给出特定索引
- C++ 重载"<<"不适用于输出"obja + objb"
- 用于测量重载运算符和成员函数的时间的函数
- 设置器不适用于重载运算符
- 如何使用 is_invocable() 创建用于重载<<打印对象的模板?
- 用于重载的泛型类成员函数
- C++创建一个标头,其中包含用于重载 ostream 的模板
- 为什么函数参数中的const限定符用于重载解析
- 为什么auto不能用于重载函数
- 对象工厂用于重载函数
- C2440用于重载函数MsgProc