简体   繁体   中英

About pointer to member function of derived class

Here's my code, and the IDE is DEV C++11

#include<iostream>
using namespace std;

class A{
    public:
        int a=15;
};
class B:public A
{

};
int main(){

    int A::*ptr=&B::a; //OK
    int B::*ptr1=&A::a; //why?
    int B::A::*ptr2=&B::a;//why?
    int B::A::*ptr3=&A::a;  //why?

} 

I have read Programming Languages — C++ and I know the type of &B::a is int A::* , but I don't realise why the next three lines will pass the compilation. And the weirdest thing to me is the syntax of int B::A::* , what's the meaning of this? I'm just a newcomer of C/C++ , so please tolerate my weird question.

Diagram representation may help you understand why it is ok and compiles int A :: * ptr =&B :: a;

int B :: * ptr1 =&A :: a;

int B :: A :: * ptr2 =&B :: a;

int B :: A :: * ptr3 =&A :: a

Interesting will be once you reinitialize the same variable in inherited class

#include<iostream>
using namespace std;

class A {
public:
    int a = 15;
};
class B :public A
{
public:
    int a = 10;
};
int main() {

    int A::*ptr = &B::a; //Waring class B a value of type int B::* cannot be 
                         //used to initialize an entity of type 'int A::*'
    int B::*ptr1 = &A::a; // why?
    int B::A::*ptr2 = &B::a;//Waring class B a value of type int B::* cannot                            
                      // be used to initialize an entity of type 'int A::*'
    int B::A::*ptr3 = &A::a;  //why?

}

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.

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