1

我有:

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。我做错了什么?!

4

3 回答 3

4

从. int m_number;_ DerivedClass否则你必须有不同的m_number成员。一个来自VirtualClass,另一个来自DerivedClass

当你添加你隐藏int m_number;DerivedClassm_number;VirtualClass

这是一个示例,它是如何工作的:

struct Foo
{
    int a;
};

struct Bar : Foo
{
    int a; //another a
};

int main()
{
    Bar *f = new Bar();
    f->a = 10; //Bar::a

    Foo *b = f;
    b->a = 20; //Foo::a

    cout << f->a << endl; //prints 10
    cout << b->a << endl; //prints 20
}
于 2012-08-15T13:59:37.693 回答
2

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

于 2012-08-15T14:01:20.997 回答
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.. 
} 
于 2012-08-15T14:46:16.683 回答