![](/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.