簡體   English   中英

當兩者具有相同的變量名稱時,從派生類訪問基類成員變量地址

[英]Accessing base class member variable address from derived class when both have the same variable name

我正在嘗試獲取基類受保護成員變量的地址。

請幫助我理解這段代碼有什么問題:

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

謝謝

吉爾

&static_cast<A*>(this)->m_不起作用,因為僅允許通過與訪問函數所屬的類相同類型的(引用或指向某個)對象來訪問受保護的基類成員(或朋友)的。

也就是說,以下是無效的,即使AB的基數

class B : public A
{
public:
    void Foo(const A& a)
    {
        auto i = a.m_; // Not valid
    }
};

參見[class.protected]

static_cast<A*>(this)創建一個指向A的指針, B不能使用它來訪問A的受保護成員。

&A::m_的問題在於它沒有獲取指向當前對象的A::m_成員的指針; 它實際上形成了一個指向成員的指針。 IE

struct A
{
    int m_;
}

int main()
{
    auto foo = &A::m_;
    A a;
    a.*foo; // Accesses the m_ member of a
}

您可以使用有點不尋常的語法&this->A::m_來避免遇到這些陷阱。

例子

您遇到的一個問題是auto p4 = &A::m_; 聲明一個指向數據成員指針 也就是說, autoauto解析為int A::* ,而不是您想要的int * 您可以通過添加括號來獲得預期的指針:

auto p4 = &(A::m_);

或者,如果您想確保獲得您想要的類型:

int * p4 = &(A::m_);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM