I'm trying to understand the consistency in the error that is thrown in this program:
#include <iostream>
class A{
public:
void test();
int x = 10;
};
void A::test(){
std::cout << x << std::endl; //(1)
std::cout << A::x << std::endl; //(2)
int* p = &x;
//int* q = &A::x; //error: cannot convert 'int A::*' to 'int*' in initialization| //(3)
}
int main(){
const int A::* a = &A::x; //(4)
A b;
b.test();
}
The output is 10 10
. I labelled 4 points of the program, but (3) is my biggest concern:
x
is fetched normally from inside a member function.
x
of the object is fetched using the scope operator and an lvalue to the object x
is returned.
- Given
A::x
returned an int
lvalue in (2), why then does &A::x
return not int*
but instead returns int A::*
? The scope operator even takes precedence before the &
operator so A::x
should be run first, returning an int
lvalue, before the address is taken. i.e. this should be the same as &(A::x)
surely? (Adding parentheses does actually work by the way).
- A little different here of course, the scope operator referring to a class member but with no object to which is refers.
So why exactly does A::x
not return the address of the object x
but instead returns the address of the member, ignoring precedence of ::
before &
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…