Why is a public const method not called when the non-const one is private?

前端 未结 11 1125
天涯浪人
天涯浪人 2020-12-25 09:18

Consider this code:

struct A
{
    void foo() const
    {
        std::cout << \"const\" << std::endl;
    }

    private:

        void foo()
           


        
11条回答
  •  借酒劲吻你
    2020-12-25 09:45

    It's important to keep in mind the order of things that happen, which is:

    1. Find all the viable functions.
    2. Pick the best viable function.
    3. If there isn't exactly one best viable, or if you can't actually call the best viable function (due to access violations or the function being deleted), fail.

    (3) happens after (2). Which is really important, because otherwise making functions deleted or private would become sort of meaningless and much harder to reason about.

    In this case:

    1. The viable functions are A::foo() and A::foo() const.
    2. The best viable function is A::foo() because the latter involves a qualification conversion on the implicit this argument.
    3. But A::foo() is private and you don't have access to it, hence the code is ill-formed.

提交回复
热议问题