Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

  1. x is fetched normally from inside a member function.
  2. x of the object is fetched using the scope operator and an lvalue to the object x is returned.
  3. 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).
  4. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
168 views
Welcome To Ask or Share your Answers For Others

1 Answer

Basically, it's just that the syntax &A::x (without variation) has been chosen to mean pointer-to-member.

If you write, for example, &(A::x), you will get the plain pointer you expect.

More information on pointers-to-members, including a note about this very property, can be found here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...