Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        3年前关闭。
                                                                                            
                
        
我正在阅读C ++入门,但是我一直在这个话题上停留。据记载

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/

10-09 23:02