0

const function body can't change members of class.The operator << will change the ostream object, if the ostream object is a member.

this is example in C++ primer(5th edition):

class PrintString{
public:
    PrintString(ostream &o = cout, char c = ' '):
        os(o), sep(c)  {} 
    void operator()(const string &s) const { os << s << sep; }
private:
    ostream &os;
    char sep;
};

why can write like "const {os << s << sep;}"? Does the operator << change the os?

  • Are you saying `os << s << sep;` works, or doesn't work? It seems like there is at least one missing "not" somewhere in this question. – ShadowRanger Nov 25 '21 at 03:38

1 Answers1

1

All that const is ensuring is your function cannot change the object pointed to by this. It doesn't say anything about whether you can call const members on os itself or not. The semantics you are looking for would be if it was declared like ostream& const os;.

Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
  • If I defined: ostream &os = cout; The sentence "os << something; " just change the "cout", do not change the os, right? – Nice Catch Nov 25 '21 at 10:48
  • `os` is a reference, to `cout`. Anything done to one will be visible through the other. I don't fully understand what you are asking. – Tanveer Badar Nov 25 '21 at 12:47
  • I think this https://stackoverflow.com/q/23436836/13316448 solves my problem. Sorry about my poor English and thank you for your time. I need to learn how to ask questions more clearly. – Nice Catch Nov 25 '21 at 22:05