gpt4 book ai didi

c++ - 复数的共轭函数

转载 作者:太空狗 更新时间:2023-10-29 19:40:03 25 4
gpt4 key购买 nike

我正在尝试创建一个共轭复数的函数例如 A(2, 3) 将通过输入 ~A 变成 A(2,-3)我在下面做了一些代码,但我想这是错误的,我希望你能帮助我解决这个问题。我在下面的代码中引用了我做错的部分。

#include <iostream>
using namespace std;
class Complex
{
private:
double real;
double imaginenary;
public:
Complex();
Complex(double r, double i = 0);

// Declaration
Complex operator~(const Complex & c) const;


Complex operator+(const Complex & c) const;
Complex operator-(const Complex & c) const;
Complex operator*(const Complex & c) const;
Complex operator*(double n) const;
friend Complex operator*(double m, const Complex & c)
{ return c * m; }
friend ostream & operator<<(ostream & os, const Complex & c);
};
Complex::Complex()
{
real = imaginenary = 0;
}

Complex::Complex(double r, double i )
{
real = r;
imaginenary = i;
}



// Definition
Complex Complex::operator~(const Complex & c) const
{
Complex conj;
conj.imaginenary = -1 * imaginenary;
conj.real = real;
}


Complex Complex::operator+(const Complex & c) const
{
Complex sum;
sum.imaginenary = imaginenary + c.imaginenary;
sum.real = real + c.real;
return sum;
}

Complex Complex::operator-(const Complex & c) const
{
Complex diff;
diff.imaginenary = imaginenary - c.imaginenary;
diff.real = real - c.real;
return diff;
}
Complex Complex::operator*(const Complex & c) const
{
Complex mult;
mult.imaginenary = imaginenary * c.imaginenary;
mult.real = real * c.real;
return mult;
}

Complex Complex::operator*(double mult) const
{
Complex result;
result.real = real * mult;
result.imaginenary = imaginenary * mult;
return result;
}
ostream & operator<<(ostream & os, const Complex & c)
{
os << "(" << c.real <<"," << c.imaginenary<<"i)";
return os;
}
int main()
{
Complex A;
Complex B(5, 40);
Complex C(2, 55);
cout << "A, B, and C:\n";
cout << A <<"; " << B << ": " << C << endl;
cout << " complex conjugate is" << ~C << endl;
cout << "B + C: " << B+C << endl;
cout << "B * C: " << B*C << endl;
cout << "10 * B: " << 10*B << endl;
cout << "B - C: " << B - C << endl;
return 0;
}

最佳答案

波浪号 (~) 运算符是一元运算符,因此它不应接受参数(它适用于 *this)。您还忘记了从 operator~ 返回一个值。

Complex operator~() const 
{
return Complex( real, -1 * imaginenary);
}

查看您的固定代码 here

顺便说一句:它的拼写是imaginary

关于c++ - 复数的共轭函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1747494/

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