在非循环对象上,为什么不用C ++调用带有public-const和private-nonconst重载的方法的const版本? [英] On a nonconst object, why won't C++ call the const version of a method with public-const and private-nonconst overloads?

查看:127
本文介绍了在非循环对象上,为什么不用C ++调用带有public-const和private-nonconst重载的方法的const版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

MSVC 2013不喜欢这样:

MSVC 2013 doesn't like this:

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

我投射到 const 引用,它的工作原理:

If I cast to a const reference, it works:

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

为什么我不能调用 const 方法对非 const 对象?

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

推荐答案

/ p>

From the standard:


13.3.3如果一个最好的可行函数存在并且是唯一的,重载解析成功并产生结果。
否则重载解析失败,调用失败。 当重载解析成功时,
在使用它的上下文中无法访问最佳可行函数(第11条),程序是
格式不正确。
p>

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.

这篇关于在非循环对象上,为什么不用C ++调用带有public-const和private-nonconst重载的方法的const版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆