On a nonconst object, why won't C++ call the const version of a method with public-const and private-nonconst overloads?

我只是一个虾纸丫 提交于 2019-12-01 13:42:54

问题


class C
{
public:
    void foo() const {}
private:
    void foo() {}
};

int main()
{
    C c;
    c.foo();
}

MSVC 2013 doesn't like this:

> error C2248: 'C::foo' : cannot access private member declared in class 'C'

If I cast to a const reference, it works:

const_cast<C const &>(c).foo();

Why can't I call the const method on the nonconst object?


回答1:


From the standard:

13.3.3 If a best viable function exists and is unique, overload resolution succeeds and produces it as the result. Otherwise overload resolution fails and the invocation is ill-formed. When overload resolution succeeds, and the best viable function is not accessible (Clause 11) in the context in which it is used, the program is ill-formed.




回答2:


The object is not const, so the non-const overload is a better match. Overload resolution happens before access checking. This ensures that overload resolution is not inadvertently changed by changing the access of a member function.



来源:https://stackoverflow.com/questions/25316779/on-a-nonconst-object-why-wont-c-call-the-const-version-of-a-method-with-publ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!