关于派生类的成员函数的指针

李亮節*_*李亮節 6 c++ pointers member-functions derived-class

这是我的代码,IDE是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?

} 
Run Code Online (Sandbox Code Playgroud)

我读过Programming Languages - C++,我知道&B::ais 的类型int A::*,但我不明白为什么接下来的三行会通过编译.而对我来说最奇怪的是它的语法 int B::A::*,这是什么意思?我只是一个新人C/C++,所以请容忍我的奇怪问题.

Har*_*ngh 1

图表表示可以帮助您理解为什么它可以并编译 int A::*ptr = &B::a;

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

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

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

有趣的是,一旦您在继承类中重新初始化相同的变量

#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?

}
Run Code Online (Sandbox Code Playgroud)