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

时间:2021-05-06 05:29:24
class C
{
public:
    void foo() const {}
private:
    void foo() {}
};

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

MSVC 2013 doesn't like this:

MSVC 2013不喜欢这样:

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

If I cast to a const reference, it works:

如果我转换为const引用,它的工作原理如下:

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

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

为什么我不能在nonconst对象上调用const方法?

2 个解决方案

#1


22  

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.

13.3.3如果存在一个最佳的可行函数并且是唯一的,则重载解析成功并将其作为结果产生。否则,重载解析失败,调用格式不正确。当重载决策成功,并且在使用它的上下文中无法访问最佳可行功能(第11条)时,程序就会形成错误。

#2


24  

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.

对象不是const,因此非const重载是更好的匹配。在访问检查之前发生过载解析。这可确保通过更改成员函数的访问权限而不会无意中更改重载决策。

#1


22  

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.

13.3.3如果存在一个最佳的可行函数并且是唯一的,则重载解析成功并将其作为结果产生。否则,重载解析失败,调用格式不正确。当重载决策成功,并且在使用它的上下文中无法访问最佳可行功能(第11条)时,程序就会形成错误。

#2


24  

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.

对象不是const,因此非const重载是更好的匹配。在访问检查之前发生过载解析。这可确保通过更改成员函数的访问权限而不会无意中更改重载决策。