以下代码无法编译:
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();
^
我g++ (tdm64-1) 5.1.0
在 Windows 上使用。
我不明白为什么f
当非 const 限定方法不可用时编译器无法回退到 const 限定方法?
我想不出允许编译器使用 const 限定方法而不是非 const 限定方法会使程序行为异常的上下文,有吗?如果不是,为什么不允许这样做?
编辑:
我已经看到了这个问题:在 c++ 中,为什么编译器在 const 也可以工作的情况下选择非常量函数?
但是在上面,这两种方法都可用,所以选择对我来说很清楚。就我而言,一种方法不可用,但编译器无法选择另一种方法,而是无法编译。