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