簡體   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