Operator overload of << needs const; produces headache

前端 未结 4 1045
天命终不由人
天命终不由人 2021-01-24 21:54

I am trying to overload operator <<, but it always need to be a const function. However, I want to change values inside this overloaded function

4条回答
  •  孤独总比滥情好
    2021-01-24 22:08

    The reason you're having trouble here is that this is an inappropriate use of operator overloading. Operator overloading is best used in these spots:

    1. Your type acts like a built-in type (for example, a mathematical type, array, or pointer), and you want to support the built-in operators on your type.
    2. Your type needs to support copying, in which case you should implement operator =.
    3. Your type needs to interface with a standard library like the STL or streams, in which case you might need to implement operator << for stream insertion or operator < to store your type in the standard container classes.
    4. You want to implement a function object, in which case you should implement operator ().

    The code you have above does not fall into any of these categories, and consequently any use of it is likely to confuse people. For example, if someone not well-versed with your project sees something like this:

    myCheck << myValue;
    

    They are likely to be thinking "oh, that's some sort of stream insertion" or "oh, that's a mathematical type getting bit-shifted over." However, in your case this code really means "have the checker object myCheck validate myValue." If that's what you want to do, then write something more explicit like

    myCheck.validate(myValue);
    

    Now, someone looking over your code can get a much better sense for how it works and what it's trying to do.

    In general, think about the Principle of Least Astonishment when writing code - code shouldn't surprise you about how it works. By using operator << in a nonstandard context, you are likely to cause programmers to misinterpret your code or have a hard time understanding what it does. Being more explicit about your intentions by using named functions rather than overloaded operators in this and related contexts makes the code more readable and decreases the chance that the code will trip up people reading it.

    Now, as for an actual answer to your question. There is no requirement that operator << be a const member function. Think about the standard streams classes like cout or ofstream; the operation

    cout << "Hello, world!" << endl;
    

    Certainly modifies cout by pushing new data into it, just as the operation

    cout << setfill('0') << left << hex;
    

    Modifies cout by changing the formatting flags. So, if you want your operator << function to mutate the object the data is pushed into, by all means go ahead and make it a non-const member function. C++ doesn't have any expectations about the constness or non-constness of any overloaded operators, so you should be perfectly fine.

提交回复
热议问题