我正在尝试创建一个共同复数的函数 例如,通过键入~A,A(2,3)将变为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;
}
答案 0 :(得分:9)
波浪号(〜)运算符是一元运算符,因此它不应接受参数(它适用于*this
)。您还忘记从operator~
返回一个值。
Complex operator~() const
{
return Complex( real, -1 * imaginenary);
}
查看您的固定代码here
BTW:拼写 imaginary 。
答案 1 :(得分:3)
很多代码,但是如果您将operator~
与例如{1}}进行比较operator+
,你会发现一个细节 - 没有回复陈述。
答案 2 :(得分:3)
试
Complex Complex::operator~() const
{
Complex conj;
conj.imaginenary = -1 * imaginenary;
conj.real = real;
return conj;
}
但是,从类定义中删除运算符并创建(朋友)函数可能更明智。隐式类型转换可以更好地工作。
答案 3 :(得分:1)
Complex Complex::operator~(const Complex & c) const
{
Complex conj;
conj.imaginenary = -1 * c.imaginenary;
conj.real = c.real;
return conj;
}
应该这样做。
虽然返回你在非全局范围内分配的任何内容并不是最好的主意,因为内存中的那个区域可以随时被覆盖。而且它是虚构的,而不是想象的那样:)
答案 4 :(得分:0)
friend Complex operator*(double m, const Complex & c) { return c * m; }
friend ostream & operator<<(ostream & os, const Complex & c);
有没有在这个问题上避免使用朋友?因为我已经从书中读到了但不太了解它。