我正在使用运算符重载实现一个复数。在程序中,用户总是以以下形式输入一个复数:
a + bi
所以,例如...
25.0 + 3.6i
假设用户将始终输入复数的实部和虚部,例如,用户将输入“5 + 0i”(而不是“5”)或“0 - 6.2i”(而不是“-6.2”一世”)。
我的问题是在 main() 我有以下代码:
ComplexNumber c1;
cin >> c1;
cout << c1;
代码打印:
0 + 0i
...当我在运行时在提示中输入“4.2 + 8.3i”时。
这是我的operator>>
课程的实现:
istream & operator>>(istream & in, ComplexNumber & n) {
string real;
string imag;
bool done = false;
int sign = 1;
string num;
in >> num;
int length;
for (int i = 0; i < num.length(); i++) {
if (num.at(i) == 'i') {
imag = num.substr((i - length), i);
}
else if (num.at(i) == '-') {
sign = -1;
}
else if (num.at(i) == ' ') {
if (!done) {
real = num.substr(i);
done = true;
}
length = 0;
}
length++;
}
n = ComplexNumber(atof(real.c_str()), atof(imag.c_str()) * sign);
return in;
}
这是我的operator<<
类的实现:
ostream & operator<<(ostream & out, const ComplexNumber & n) {
n.print(out);
return out;
}
这是我对 ComplexNumber 成员类 print() 的实现:
void ComplexNumber::print(ostream & out) const {
if (imag >= 0)
out << real << " + " << imag << "i";
else
out << real << " - " << (-1 * imag) << "i";
}
这是我的 ComplexNumber 头文件以获取更多详细信息:
#ifndef COMPLEXNUMBER_H
#define COMPLEXNUMBER_H
#include <iostream>
using namespace std;
class ComplexNumber {
public:
// constructors
ComplexNumber();
ComplexNumber(double real_part, double imaginary_part);
ComplexNumber(const ComplexNumber & rhs);
// named member functions
void print(ostream & out = cout) const;
bool equals(const ComplexNumber & rhs) const;
// assignment operators
const ComplexNumber & operator=(const ComplexNumber & rhs);
const ComplexNumber & operator+=(const ComplexNumber & rhs);
const ComplexNumber & operator-=(const ComplexNumber & rhs);
const ComplexNumber & operator*=(const ComplexNumber & rhs);
private:
double real;
double imag;
};
// arithmetic operators
ComplexNumber operator+(const ComplexNumber & lhs, const ComplexNumber & rhs);
ComplexNumber operator-(const ComplexNumber & lhs, const ComplexNumber & rhs);
ComplexNumber operator*(const ComplexNumber & lhs, const ComplexNumber & rhs);
// relational operators
bool operator==(const ComplexNumber & lhs, const ComplexNumber & rhs);
bool operator!=(const ComplexNumber & lhs, const ComplexNumber & rhs);
// I/O operators
ostream & operator<<(ostream & out, const ComplexNumber & n);
istream & operator>>(istream & in, ComplexNumber & n);
#endif
对我的实现有任何帮助都会很棒。