Rationale of enforcing some operators to be members

后端 未结 2 661
无人共我
无人共我 2020-11-28 12:29

There are 4 operators in C++ which can be overloaded but cannot be overloaded as freestanding (aka nonmember, standalone) functions. These operators are:

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 13:11

    This thread on comp.std.c++ discusses the question.

    Francis Glassborow, who was on the committee, stated:

    The language designers did not want to support conversions and promotions on the left-hand operand of operator =, nor such on the operand of () and [].

    Trying to avoid the situation where:

    class A {};
    
    class B { B(A& a) {} };
    
    int operator()(B const& b) { return 0; }
    
    
    int main(void)
    {
        A a;
    
        // This works even though A doesn't have a () operator
        // It creates a temporary B and calls operator()(B& b)
        return a();                   
    }
    

提交回复
热议问题