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

时间:2017-07-21 14:19:02

标签: c++ pointers derived-class member-functions

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

} 

我已阅读编程语言 - C ++,我知道&B::a的类型是int A::*,但我不知道为什么接下来的三行会通过编译。 对我来说最奇怪的是int B::A::*的语法,这是什么意思?我只是C/C++的新人,所以请容忍我的奇怪问题。

1 个答案:

答案 0 :(得分: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?

}
相关问题