Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

c++ - Pointer-to-member confusion

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

1.4m articles

1.4m replys

5 comments

56.8k users

...