繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM