重载运算符>>和istream格式

时间:2014-03-22 19:43:21

标签: c++

我有两个问题:

  1. 我正在尝试重载istream运算符>>接受“(a,b)”的输入并设置a = real和b = imaginary。我可以跳过第一个(使用input.ignore(),但输入的数字可以是任何大小,所以我不知道如何只读取“a”到逗号到真实,只是b到虚构。

    < / LI>
  2. 当我尝试设置number.real时,我得到错误成员Complex :: real是不可访问的。

  3. 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 <<
    }
    

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

如果我理解正确,您只需将值直接读入数据成员:

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;
}