![](/img/trans.png)
[英]Access derived member instead of base member with same name in derived class
[英]derived class has same member variable name as base class
#include<iostream>
using namespace std;
class A
{
protected:
int m_nValue;
public:
A(int nValue):m_nValue(nValue)
{
cout << m_nValue << endl;
}
};
class B: public A
{
public:
B(int nValue): A(m_nValue)
{
cout << m_nValue << endl;
}
int getValue()
{
return m_nValue;
}
};
int main()
{
B b(4);
cout << b.getValue() << endl;
return 0;
}
在這里,在上面的程序中,我沒有在Derived類中再次聲明m_nValue
。 在輸出中,我僅看到顯示垃圾值,而不顯示值“ 4”。 請解釋一下。
您正在嘗試使用m_nValue
本身初始化m_nValue
。 根本不使用參數nValue
(傳入值4
)。 這就是m_nValue
僅具有垃圾值的原因。
你可能想要
B(int nValue): A(nValue)
{
cout << m_nValue << endl;
}
B(int nValue): A(nValue)
您應該使用nValue
而不是m_nValue
初始化A
您的構造函數被B(int nValue): A(m_nValue)
。 您沒有使用nValue
將其傳遞給A
構造函數,而是使用了未初始化的實例變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.