繁体   English   中英

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

[英]About pointer to member function of 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?

} 

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

图表表示可以帮助您理解为什么它可以正常编译 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?

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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