如果存在非常量限定的私有方法,为什么不能在非常量对象上调用常量限定的方法

Why cannot a const qualified method be called on a non const object if a non const qualified private method exists?

本文关键字:常量 非常 对象 调用 不能 方法 有方法 存在 如果 为什么      更新时间:2023-10-16

以下代码不编译:

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

我不明白为什么当非常量限定方法不可用时,编译器不能回到常量限定方法f

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

编辑:

我已经看到了这个问题:在c++中,当常量也可以工作时,编译器为什么选择非常量函数?

但在上面,两种方法都可用,所以我很清楚选择。在我的情况下,一种方法不可用,但编译器无法选择另一种方法,相反,它无法编译。

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