andrey
andrey

Reputation: 81

error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'

Getting this error and I'm pretty sure it's in the operator<< function. Both prints are public.

void CRational::print() const
{
    print(cout);
}

void CRational::print(ostream & sout) const
{
    if(m_denominator == 1)
        cout << m_numerator;
    else
        cout << m_numerator << "/" << m_denominator;
}

ostream operator<<(ostream & sout,const CRational a)
{
    a.print();

    return sout;
}

CRational operator++() // prefix ++x
{
    m_numerator += m_denominator;
    return *this;
}

in main:
cout << "e before: " << e << ", \"cout << ++e\" : " << ++e << " after: " << e << endl; 

Upvotes: 8

Views: 7955

Answers (3)

Keith
Keith

Reputation: 6834

You need to return the ostream by reference, not value. Its trying to call a constructor. Might as well pass 'a' as reference as well:

ostream& operator<<(ostream & sout,const CRational& a)

I also note that the print method is probably wrong. It has sout passed as the name of the stream but is then implemented using cout directly. It should be

void CRational::print(ostream & sout) const
{
    if(m_denominator == 1)
        sout << m_numerator;
    else
        sout << m_numerator << "/" << m_denominator;
}

Upvotes: 11

user470379
user470379

Reputation: 4889

operator<< should return a reference to an ostream: ostream& operator<<...

Also your functions are kinda messed up. Instead of using cout, you should used the passed in ostream which you've named sout.

Upvotes: 1

James McNellis
James McNellis

Reputation: 355079

ostream operator<<(ostream & sout,const CRational a)
       ^ You are trying to return by value

Streams are not copyable, so you can't return one by value. You need to return the stream by reference (std::ostream&).

Also, you should probably be outputting to sout in your CRational::print(ostream&) function (otherwise, why take it as an argument?) and you should probably be passing sout when you call a.print() in your operator<< overload (otherwise, the overload doesn't really do what an idiomatic operator<< overload for a stream is supposed to do).

Upvotes: 4

Related Questions