[英]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_
不起作用,因為僅允許通過與訪問函數所屬的類相同類型的(引用或指向某個)對象來訪問受保護的基類成員(或朋友)的。
也就是說,以下是無效的,即使A
是B
的基數
class B : public A
{
public:
void Foo(const A& a)
{
auto i = a.m_; // Not valid
}
};
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_
來避免遇到這些陷阱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.