Creating object with constant parameters from stream

前端 未结 4 2065
我在风中等你
我在风中等你 2021-01-18 05:02

let us assume I have a class with

#include 
using namespace std;

class Test{
    public:
        friend istream& operator >> (istr         


        
4条回答
  •  误落风尘
    2021-01-18 05:55

    You declared dummy const, so obviously mutating it during the lifetime of Test would break the contract about const.

    This is what operator>> is doing at the moment and the compiler is helpfully trying to prevent you from breaking that contract.

    Does operator>> actually do the initialization of Test?

    If operator>> should only do the initialization, not overwriting, of Test, then you should turn operator>> into a factory function, as demonstrated in gwiazdorrr's "recommended way".

    If, on the other hand, operator>> should overwrite Test, then you're breaking the contract about the constness of dummy, and that's just bad. Therefore, dummy should be non-const.

    Does dummy really need to be const?

    You could simply enforce the immutability of dummy through the interface of Test. Though in this case it could still be mutated inside the class, which is probably what you're trying to avoid.

提交回复
热议问题