简体   繁体   English

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

[英]About pointer to member function of derived class

Here's my code, and the IDE is DEV C++11 这是我的代码,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?

} 

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. 我读过Programming Languages - C ++,我知道&B::a的类型是int A::* ,但我没有意识到为什么接下来的三行会通过编译。 And the weirdest thing to me is the syntax of int B::A::* , what's the meaning of this? 对我来说最奇怪的是int B::A::*的语法,这是什么意思? I'm just a newcomer of C/C++ , so please tolerate my weird question. 我只是C/C++的新手,所以请容忍我的奇怪问题。

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?

}

暂无
暂无

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

相关问题 将派生类中的成员函数的指针强制转换为抽象成员函数的指针 - cast a pointer to member function in derived class to a pointer to abstract member function 如果基础 class 指针无法访问派生的 class 成员 function,那么多态有什么方便之处呢? - If base class pointer cannot access derived class member function, then what is so convenient about polymorphism? 保存指向派生类的成员函数的指针 - Save a pointer to member function of derived class 指向派生类成员函数的指针,但不指向派生(虚拟)函数 - Pointer to member function of derived class, but not derived(virtual) function 使用基类函数指针访问派生类成员函数 - Using base class function pointer to access derived class member function 如何注册派生的 class 成员 function 指针与基数 class - How to register a derived class member function pointer with a base class 在派生类的对象上使用指向基类的成员函数的指针 - Using pointer to member function of a base class on object of derived class 函数在派生类中但不在基类中,指向基类的指针--&gt;“不是成员”错误 - function in derived but not in base class, pointer to base --> "not a member" error 成员函数指针转换,从派生类到基类 - Member function pointer cast, from Derived to Base class 如何基于派生类的指针找到成员函数? - How is a member function found based on this pointer of the derived class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM