C++ 派生类与基类具有相同的成员变量名
这里,在上面的程序中,我不再在派生类中声明m_nValue。在输出中,我只看到显示垃圾值,而不是显示值4。 请解释一下C++ 派生类与基类具有相同的成员变量名,c++,C++,这里,在上面的程序中,我不再在派生类中声明m_nValue。在输出中,我只看到显示垃圾值,而不是显示值4。 请解释一下 #include<iostream> using namespace std; class A { protected: int m_nValue; public: A(int nValue):m_nValue(nValue) { cout << m_nValue << endl; } };
#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;
}
您应该使用nValue而不是m_nValue初始化
您应该使用nValue而不是m_nValue初始化构造函数。您的构造函数在nValue:Am_nValue中有错误。您没有使用nValue将其传递给构造函数,而是使用未初始化的实例变量。您的构造函数在Bint nValue:Am\u nValue中安装了错误。您没有使用nValue将其传递给构造函数,而是使用未初始化的实例变量。您正在尝试使用m\u nValue本身初始化m\u nValue。在值4中传递的参数nValue根本不使用。这就是为什么m_nValue只有垃圾值 你可能想要
B(int nValue): A(nValue)
您试图用m_nValue本身初始化m_nValue。在值4中传递的参数nValue根本不使用。这就是为什么m_nValue只有垃圾值 你可能想要
B(int nValue): A(nValue)