如果存在非常量限定的私有方法,为什么不能在非常量对象上调用常量限定的方法
Why cannot a const qualified method be called on a non const object if a non const qualified private method exists?
以下代码不编译:
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++中,当常量也可以工作时,编译器为什么选择非常量函数?
但在上面,两种方法都可用,所以我很清楚选择。在我的情况下,一种方法不可用,但编译器无法选择另一种方法,相反,它无法编译。
因为它首先通过重载解析来选择一个方法。一旦确定了要调用的一个方法,就会检查您是否具有正确的访问权限。换句话说,访问说明符不会影响重载解析。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- OpenGL大的3D纹理(>2GB)非常慢
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 使用常量键但非常量值进行映射
- 为什么`is_open()`非常常量
- 从getter方法返回常量和非常量值
- 阻止const类函数在引用成员上调用非常常量类函数
- C++初始化非常大的常量数组,最佳实践
- 提高c++中非常大的常量的可读性