У меня есть два вопроса:
Я пытаюсь перегрузить оператор istream >> принять вход "(a, b)" и установить a = real и b = мнимый. Я могу пропустить первый (с input.ignore(), но введенный номер может быть любого размера, поэтому я не уверен, как читать только "а" до запятой в реальном и просто b в мнимой.
Когда я пытаюсь установить number.real, я получаю член ошибки Complex :: real недоступен.
заголовок
class Complex
{
friend istream &operator>>(istream &, Complex &);
friend ostream &operator<<(ostream &, const Complex &);
private:
double real;
double imaginary;
};
источник
#include <iostream>
#include <string>
#include <iomanip>
#include "complex.h"
using namespace std;
Complex::Complex(double realPart, double imaginaryPart)
:real(realPart),
imaginary(imaginaryPart)
{
}
istream &operator>>(istream &input, Complex &number)
{
string str;
int i = 0;
input >> str;
while (str[i] != ','){
i++;
}
input.ignore(); // skips the first '('
input >> setw(i - 1) >> number.real; //?? "Enter a complex number in the form: (a, b)
}
главный
#include <iostream>
#include "Complex.h"
using namespace std;
int main()
{
Complex x, y(4.3, 8.2), z(3.3, 1.1), k;
cout << "Enter a complex number in the form: (a, b)\n? ";
cin >> k; // demonstrating overloaded >>
cout << "x: " << x << "\ny: " << y << "\nz: " << z << "\nk: "
<< k << '\n'; // demonstrating overloaded <<
}
Если я правильно понимаю, все, что вам нужно сделать, это прочитать значения непосредственно в элементах данных:
istream& operator>>(istream& input, Complex& number)
{
input.ignore(); // ignore the first (
input >> number.real;
input.ignore(); // ignore the ,
input >> number.imaginary;
input.ignore(); // ignore the next )
return input;
}
Я думаю, что один ответ может состоять в том, чтобы написать std::streambuf
а затем использовать std::streambuf
в унаследованном std::iostream