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

时间:2016-06-02 01:19:55

标签: c++

#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。在输出中,我看到只显示垃圾值而不是显示值&#34; 4&#34;。 请解释一下。

3 个答案:

答案 0 :(得分:3)

您尝试使用m_nValue本身初始化m_nValue。根本不使用参数nValue(在值4中传递)。这就是m_nValue只有垃圾值的原因。

你可能想要

B(int nValue): A(nValue)
{
    cout << m_nValue << endl;
}

答案 1 :(得分:2)

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

//class declaration

class Person{
public:
    string lastName;
    string firstName;
};

//variables

int entry; // defined in other function
string choice; //defined in other function

//arrays

Person nameArray[10];

//function declarations

void sortView(){

    sort(nameArray[0].lastName.begin(), nameArray[0].lastName.end() + entry);

    for (int i = 0; i < entry; i++){
        cout << nameArray[i].lastName;
        cout << ", ";
        cout << nameArray[i].firstName;
        cout << endl;
    }
};

您应该使用B(int nValue): A(nValue) 而不是A

初始化nValue

答案 2 :(得分:2)

您的构造函数被标记为B(int nValue): A(m_nValue)。您没有使用nValue将其传递给A构造函数,而是将其传递给未初始化的实例变量。

相关问题