c++ - 为什么在复制对象时忽略顶级常量?

标签 c++ constants

<分区>

我正在阅读 C++ primer,但我一直停留在这个主题上。据记载

int i=0;
const int ci=42; //const is top level.
const int *p2=&ci; //const is low level.
const int *const p3=p2; //rightmost const is top level,left one is low level. 
int *p=p3 //error.
p2=p3 //ok:p2 has the same low level constant qualification as p3.
int &r=ci; //error: can't bind an ordinary int to const int object
const int &r2=i; //ok:can bind const int to plain int.

现在如果在最后一条语句中忽略了顶级常量,那么它应该给出一个错误,因为 &r2 和 i 的低级常量限定是不一样的。为什么最后的陈述是正确的??

最佳答案

你一口气问十亿个问题,但我会总结一下。

  • 这些:

    int &r=ci; //error: can't bind an ordinary int to const int object
    const int &r2=i; //ok:can bind const int to plain int.
    

    遵守reference initialization的规则.左侧需要具有与右侧相同或大于右侧的 cv 资格。

  • 这些:

    const int *p2=&ci; //const is low level.
    const int *const p3=p2; //rightmost const is top level,left one is low level. 
    int *p=p3 //error.
    p2=p3 //ok:p2 has the same low level constant qualification as p3.
    

    遵守qualification conversions的规则.本质上,他们试图保持 const 的正确性。像 p = p3 这样的赋值肯定不会做。

我认为如果你放弃“顶级”和“低级”const 的东西你会更容易理解规则,因为它们显然不会帮助你理解什么是发生在这里。

关于c++ - 为什么在复制对象时忽略顶级常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37716868/

相关文章:

c++ - Getline 获取 vector 字符串

c++ - 非模板类中的某些模板函数

c++ - 强制程序/线程使用 100% 的处理器资源

c++ - std::unique_ptr 转移 const 对象的所有权

c++ - localtime() 比 gmtime() 多花费 24 倍 linux 上的性能问题

c++ - GCC 编译器错误 : "redefinition...previously defined"

c++ - 在初始化列表中调用私有(private)函数的情况下,它是未定义的行为吗?

编译器#警告: print enum value

c++ - 静态 const 成员的 const_cast

php - 数据库常量表与代码中的常量