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
.
You code is the same situation, except that instead of integer you have pointer to integer:
m
is const so mx
is const. The x
is const, ie x
cannot be modified (via m
). In stricter terms mx
is of type int * const
ie constant pointer to integer.
int *r = m.x
Here you just initialize the pointer r
with the value of the pointer mx
. The fact that mx
is const is not an issue. Both types without their top level cv are identical: pointer to (mutable) integer.
const A &m = a; // clause 1 - Is this top-level const?
Yes
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.