关于派生类成员函数指针

6

以下是我的代码,开发环境是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
@Ron 啊,这是 [mcve]。ptr 的类型是 int A::*ptr2 的类型是 int B::A::*,等等。正如你所看到的:OP 发布的代码可以编译通过,他们只是对为什么它能编译通过感到困惑。 - Algirdas Preidžius
@AlgirdasPreidžius 确实。我改正我的立场。 - Ron
1
你为什么认为它们不能通过编译? - n. m.
我认为int B::A::*只是一种间接层次,实际上是int A::* - Ron
1个回答

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?

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接