复数的加法运算符重载
Addition operator overloading for complex numbers
我编写了以下代码来对复数进行基本运算的运算符重载,这里我只放了加法。运行它时,我收到数万亿个错误。我已经看到了其他几篇关于此的帖子,但我刚刚开始学习C++。如果您能大致指出我在运算符重载中犯的错误,我将不胜感激(这与调试无关,但我希望得到一些一般性解释,因为我已经看到了相同运算符重载的示例,但无法理解几个功能,例如使用指针和 const(。提前谢谢。
#include<iostream>
using namespace std;
class Complex
{
private:
double real;
double imaginary;
public:
Complex(double r, double i);
// addition
Complex operator+(Complex c1, Complex c2);
};
Complex::Complex(double r, double i)
{
real = r;
imaginary = i;
}
Complex Complex::operator+(Complex c1, Complex c2)
{
Complex result;
result.r = c1.r + c2.r;
result.i = c1.i + c2.i;
return result;
}
ostream ostream::operator<<(ostream out, Complex number)
{
out << number.r << "+" << number.i << endl;
}
int main() {
Complex y, z;
Complex sum;
y = Complex(2, 4);
z = Complex(3, 0);
cout << "y is: " << y << endl;
cout << "z is: " << z << endl;
sum = y+z;
cout << "The sum (y+z) is: " << sum << endl;
return 0;
}
这里有大量的错误,从不正确的重载运算符尝试到使用错误名称的数据成员。 我会逐步完成我所看到的。
将二进制operator+
定义为成员函数时,它只需要一个参数,即右侧参数+
(左侧隐式*this
(。
此外,您的运算符使用不存在的字段 r
和 i
- 您可能是指 real
和 imaginary
。
class Complex
{
// ...
public:
// Wrong, will cause compile-time errors:
// Complex operator+(Complex c1, Complex c2);
// Right:
Complex operator+(Complex c);
};
Complex Complex::operator+(Complex c)
{
Complex result;
result.real = real + c.real;
result.imaginary = imaginary + c.imaginary;
return result;
}
或者,您可以将运算符定义为自由函数而不是类的成员,但您必须使其成为类的好友,因为它访问私有成员:
class Complex
{
// ...
friend Complex operator+(Complex, Complex);
};
Complex operator+(Complex c1, Complex c2)
{
Complex result;
result.real = c1.real + c2.real;
result.imaginary = c1.imaginary + c2.imaginary;
return result;
}
同样,std::ostream
的operator<<
重载应该是一个免费函数,需要修复才能使用 real
和 imaginary
。 但是,由于这些成员是Complex
私有的,除非您将此运算符设为Complex
的朋友,否则这将失败。 由于ostream
是抽象类型,不能接受或按值返回实例,因此需要使用引用。 此外,您实际上不会返回任何内容。
class Complex
{
// ...
friend ostream & operator<<(ostream &, Complex);
};
ostream & operator<<(ostream & out, Complex number)
{
out << number.real << "+" << number.imaginary << endl;
return out;
}
您的 Complex
类缺少默认构造函数,因此您无法像 Complex c;
一样声明变量,因为这需要存在默认构造函数:
class Complex
{
// ...
public:
Complex();
};
Complex::Complex() : real(0), imaginary(0) { }
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板