简体   繁体   English

C++:class 类型的 const 是否始终是顶级 const?

[英]C++ : Is class type const always a top-level const?

Here are the following code:以下是以下代码:

#include <iostream>
using namespace std;

class A {
public:
   int *x;
};

int main() {
   int b=100;
   A a;
   a.x = &b;
   const A &m = a; // clause 1 - Is this top-level const? 
   int *r = m.x; // *r has no const yet allowed. Is it due to reference m being top level const?
}

Any help appreciated.任何帮助表示赞赏。
Thanks谢谢

int const ca = 24;
int a = ca;

You would expect this to compile right?你会期望这个编译正确吗? And indeed it does.确实如此。 Here I initialized a integer with the value 24 .在这里,我用值24初始化了一个 integer 。

You code is the same situation, except that instead of integer you have pointer to integer:您的代码是相同的情况,除了 integer 您有指向 integer 的指针:

m is const so mx is const. m是 const,所以mx是 const。 The x is const, ie x cannot be modified (via m ). x是常量,即x不能被修改(通过m )。 In stricter terms mx is of type int * const ie constant pointer to integer.更严格地说, mxint * const类型,即指向 integer 的常量指针。

int *r = m.x

Here you just initialize the pointer r with the value of the pointer mx .在这里,您只需使用指针mx的值初始化指针r The fact that mx is const is not an issue. mx是 const 的事实不是问题。 Both types without their top level cv are identical: pointer to (mutable) integer.没有顶级 cv 的两种类型都是相同的:指向(可变)integer 的指针。


const A &m = a; // clause 1 - Is this top-level const?

Yes是的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM