Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 派生类与基类具有相同的成员变量名_C++ - Fatal编程技术网

C++ 派生类与基类具有相同的成员变量名

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

这里,在上面的程序中,我不再在派生类中声明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;
    }
};
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)