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

前端 未结 11 1170
天涯浪人
天涯浪人 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 10:00

    Since the implicit this pointer is non-const, the compiler will first check for the presence of a non-const version of the function before a const version.

    If you explicitly mark the non-const one private then the resolution will fail, and the compiler will not continue searching.

提交回复
热议问题