无法获取派生类成员的值

时间:2012-08-15 13:58:23

标签: c++ inheritance interface

我有:

VirtualClass : public QObject
{
public:
    int m_number;
}

DerivedClass : public VirtualClass 
{
public:
    DerivedClass(int number) : m_number(number) {};
    int m_number;
    // some content goes here..
}

客户代码:

f(VirtualClass* instance)
{
std::cout << instance->m_number;
}

DerivedClass der(100);

我希望f(der) 返回与DerivedClass相关的m_number ,但是*我得到了VirtualClass *的m_number。 我做错了什么?!!

3 个答案:

答案 0 :(得分:4)

int m_number;移除DerivedClass。否则,您必须拥有不同的m_number成员。一个来自VirtualClass,另一个来自DerivedClass

int m_number;中添加DerivedClass隐藏m_number;的{​​{1}}

以下是一个如何运作的示例:

VirtualClass

答案 1 :(得分:2)

您已宣布int m_number;两次。你应该只声明一次。

答案 2 :(得分:2)

spin_eight: 如果要在VirtualClass上提供适当的构造函数,并从派生的初始化列表中调用它,可以保留初始化列表,如下所示:

VirtualClass : public QObject 
{ 
 public: 
 VirtualClass(int number) : m_number(number) { }
 int m_number; 
}

DerivedClass : public VirtualClass
{
 public: 
 DerivedClass(int number) : VirtualClass(number) {}; 
 // some content goes here.. 
}