C++ 当派生类和基类具有相同的变量名时,从派生类访问基类成员变量地址
我正在尝试获取受基类保护的成员变量的地址 请帮助我了解此代码的错误:C++ 当派生类和基类具有相同的变量名时,从派生类访问基类成员变量地址,c++,C++,我正在尝试获取受基类保护的成员变量的地址 请帮助我了解此代码的错误: class A { protected: int m_; }; class B : public A { public: void Foo() { auto p1 = m_; // works but not what I want (B's member) auto p2 = &m_; //
class A
{
protected:
int m_;
};
class B : public A
{
public:
void Foo()
{
auto p1 = m_; // works but not what I want (B's member)
auto p2 = &m_; // works but not the the address which I'm looking for (B's member)
auto p3 = A::m_; // works but still not the address of the variable (A's member but not the address)
auto p4 = &A::m_; // doesn't work -> int A::m_’ is protected within this context
auto p5 = static_cast<A*>(this)->m_; // doesn't work -> int A::m_’ is protected within this context
auto p6 = &static_cast<A*>(this)->m_; // doesn't work -> int A::m_’ is protected within this context
}
private:
int m_;
};
A类
{
受保护的:
int m_;
};
B类:公共A
{
公众:
void Foo()
{
auto p1=m_;//工作正常,但不是我想要的(B的成员)
auto p2=&m_;//工作正常,但不是我要查找的地址(B的成员)
auto p3=A::m_;//工作,但仍然不是变量的地址(A的成员,但不是地址)
auto p4=&A::m_;//不起作用->int A::m_;'在此上下文中受保护
auto p5=static_cast(this)->m_;//不起作用->int A::m_2;在该上下文中受保护
auto p6=&static_cast(this)->m_;//不起作用->int A::m_2;在该上下文中受保护
}
私人:
int m_;
};
谢谢
Gil&静态演员阵容
static\u cast您遇到的一个问题是auto p4=&A::m代码>声明一个。也就是说,auto
将自身解析为inta::*
,而不是您想要的int*
。您可以通过添加括号获得所需的指针:
auto p4 = &(A::m_);
或者,如果您想确保获得您想要的类型:
int * p4 = &(A::m_);
是 啊这就是我一直在寻找的答案。。。谢谢
auto p4 = &(A::m_);
int * p4 = &(A::m_);