【问题标题】:Why cannot a const qualified method be called on a non const object if a non const qualified private method exists? [duplicate]如果存在非 const 限定的私有方法,为什么不能在非 const 对象上调用 const 限定的方法? [复制]
【发布时间】:2016-04-16 18:50:19
【问题描述】:

以下代码无法编译:

struct A {
    void f () const { }
private:
    void f () { }
};

int main () {
    A a_nc;
    const A a_c;
    a_nc.f();
    a_c.f();
    return 0;
}

错误:

test.cpp: In function 'int main()':
test.cpp:4:10: error: 'void A::f()' is private
     void f () { }
          ^
test.cpp:10:12: error: within this context
     a_nc.f();
            ^

我在 Windows 上使用g++ (tdm64-1) 5.1.0

我不明白为什么当非 const 限定方法不可用时,编译器无法回退到 const 限定方法 f

我想不出允许编译器使用 const 限定方法而不是非 const 限定方法会使程序行为异常的上下文,有吗?如果不是,为什么不允许这样做?

编辑:

这个问题我已经看过了:In c++, why does the compiler choose the non-const function when the const would work also?

但是在上面,这两种方法都可用,所以选择对我来说很清楚。就我而言,一种方法不可用,但编译器无法选择另一种方法,而是无法编译。

【问题讨论】:

  • 我没有答案,但你可以通过使用类方法指针来强制它。
  • 重新编辑:这就是我提出不同问题的原因。
  • @T.C.您的副本清楚地回答了我的问题,谢谢。有没有办法不在这个问题的顶部显示另一个?
  • @holt 阅读链接中的“c++ 注释”位,该链接作为副本关闭。它说明了 C++ 中需要这种行为的确切要求。
  • @xaxxon “c++ 注释”位指出编译器选择了最接近的匹配,但我正在寻找的是为什么没有将访问考虑到“最接近的匹配”定义中。引用自 T.C. 中的引用。发布清楚地回答这部分。

标签: c++ overloading overload-resolution private-methods const-method


【解决方案1】:

因为它首先通过重载决议选择一个方法。一旦确定了要调用的一种方法,就会检查您是否具有正确的访问权限。换句话说,访问说明符不会影响重载决议。

【讨论】:

    猜你喜欢
    • 2016-12-26
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    相关资源
    最近更新 更多