Why operator= returns reference not const reference

后端 未结 6 571
轻奢々
轻奢々 2020-12-11 05:29

The original question is related to overloading operator= and I like to share my findings as it was nontrivial for me to find them. I cannot imagine reasonable example to us

6条回答
  •  我在风中等你
    2020-12-11 06:21

    I've spent some time and here is my example:

    class A
    {
    public:
        const A& operator= (const A& a) {return *this;}
    };
    
    int main(int argc, char* argv[])
    {
        A a1;
        A& a2 = a1;
        A& a3 = (a2 = a1);
    }
    

    and the compiler output: : error C2440: 'initializing' : cannot convert from 'const A' to 'A &'

    I've checked it on MS VS 2010, but is it true on other platforms? And if this example is sufficient condition for = to be non const?

提交回复
热议问题