简体   繁体   中英

“Essential C++”: Providing Class Instances of the iostream Operators

From Essential C++: 4.10 Providing Class Instances of the iostream Operators

Often, we wish to both read and write objects of a class. For example, to display our trian class object, we want to be able to write

cout << train << endl;

To support this, we must provide an overloaded instance of the output operator:

ostream& operator<< (ostream &os, const Triangular &rhs)
{
    os << "(" << rhs.beg_pos() << "," << rhs.length() << ")";
    rhs.display(rhs.length(), rhs.beg_pos(), os);
    return os;
}

We return the same ostream object passed into the function. This allows multiple outptu operators to be concatenated. Both objects are passed by reference. The ostream operand is not declared as const because each output operation modifies the internal state of the ostream object.

I'm kind of confused why the ostream operand cannot be declared as const. If the output operator is declared as the following:

const ostream& operator<< (const ostream &os, const Triangular &rhs)

Is there any problem with the above declaration?

Thanks

The problem is that if the ostream argument (or conversely istream ) was a constant reference, then the operator would not be able to modify the stream object. Insertion/extraction to the streams modify the stream state, so the existing operator<< are non-const operations. That in turn means that while you can declare and even define :

std::ostream const & operator<<( std::ostream const & s, Type const & t );

The problem is that the definition would not be able to actually write anything at all into the stream:

std::ostream const & operator<<( std::ostream const & s, Type const & t ) {
   s << "Hi";     // Error: operator<<( std::ostream&, const char*) requires a
                  //        non-const `std::ostream&`
   return s;      // This is fine
}

When outputting the variable rhs , some data members inside ostream& os such as output buffer or position of file write if os is a ofstream must be modified.

Declaring os as const forbids such a modification.

And, as shown here , if os is declared as const , then you cannot use it to output primitive data types since none of ostream::operator<<() is declared as constant member function.

是的,可以通过调用<<来修改ostream参数os。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM