对于用户定义的类,我以以下方式为<<重载了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/

10-10 21:38