c++ - 用户定义类的输入流

标签 c++ operator-overloading iostream cin istream

对于用户定义的类,我重载了 << cout 的运算符如下

ostream& operator<<(ostream& os, const myObject& obj_)
{
    if (obj_.somefloat != 0)
        os << "(" << obj_.somefloat << ")";
    else if ( obj_.oneint != 0 && obj_.twoint != 0)
        os << "(" << obj_.oneint << "#" << obj_.twoint << ")";
    else    
        os << "Empty Object";
    return os;
}

如何重载>>相当于 cin 的运算符

最佳答案

这应该有效:

std::istream& operator>>( std::istream& in, myObject& obj_ )
{
    char c;
    if( in >> c )
    {
        if( c == '(' )
        {
            float f;
            if( in >> f >> c ) // f reads also an int
            {
                if( c == ')' )  // single float format
                {
                    if( f != 0.0 )
                        obj_.somefloat = f;
                    else
                        in.setstate( std::ios_base::failbit );
                }
                else if( c == '#' ) // two int format
                {
                    if( float(int(f)) != f  )
                        in.setstate( std::ios_base::failbit );
                    else
                    {
                        obj_.somefloat = 0;
                        obj_.oneint = int(f);
                        if( in >> obj_.twoint >> c && (c != ')' || (obj_.oneint == 0 && obj_.twoint == 0) ) )
                            in.setstate( std::ios_base::failbit );
                    }
                }
                else
                    in.setstate( std::ios_base::failbit );
            }
        }
        else if( c == 'E' ) // "Empty Object"
        {
            const char* txt="Empty Object";
            ++txt; // 'E' is already read
            for( ; *txt != 0 && in.get() == *txt && in; ++txt )
                ;
            if( *txt == char(0) )
            {
                obj_.somefloat = 0;
                obj_.oneint = 0;
                obj_.twoint = 0;
            }
            else
                in.setstate( std::ios_base::failbit );
        }
        else
            in.setstate( std::ios_base::failbit );
    }
    return in;
}

关于c++ - 用户定义类的输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21773291/

相关文章:

c++ - 使用包含类的动态实例化后调用 C++ 重载运算符 [] 似乎不起作用

c++ - 在类中为结构重载 operator=

c++ - 模板类中的运算符 "()"

C++ 输入性能

double 类型的 C++ 变量总是将它们的值更改为 -9,25596e+061

c++ - 从类返回不正确的值

c++ - 游戏编程

c++ - 发送 GetItem 请求时出现 HTTP 401 未经授权的错误

c++ - gcc/g++ 可以在忽略我的寄存器时告诉我吗?

c++ fstream 在 1 个函数之后不起作用(通过引用)