Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 当派生类和基类具有相同的变量名时,从派生类访问基类成员变量地址_C++ - Fatal编程技术网

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_);