重载乘法运算符
Overloading Multiplication Operator
我正在为我的 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;
}
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板