0

我正在使用 c++ 学习 OOP,并且遇到了我不太了解的情况。

{了解公共数据成员的不良做法并假设指针不为 NULL}:

...

class Foo {
    public: int a = 0;
}

class Bar: public Foo {
   public: int a = 1;
}

void display (Foo * in) {
    if(in->a)
        cout << "I'M A BAR" << endl;
    else
        cout << "I'M A FOO" << endl;
}

int main() {
    Foo * BAR = new Bar;
    display(BAR); //Displays "I'M A FOO"
    return 0;
}

经过一番修改后,我发现如果我改为使用构造函数将非 const int a 值分别设置为 0 和 1,并且还从构造函数中输出值,我看到该值实际上在 BAR 中设置为 1,但是在显示函数中被评估为 0。

如果这没有意义,我很抱歉,我怀疑我是否真的理解得足够好,无法提出正确的问题,但我想知道为什么 BAR 不被视为显示器内的酒吧以及如何让它这样做(如果可能的话,同时使用基类指针作为参数)。

4

1 回答 1

4

Your code makes sense, but it is probably not what you think.

Your class Bar has two members called a, one is Bar::a, and one is Bar::Foo::a, the member of the Foo base class.

When you access either a Foo or a Bar object through a pointer, like p->a, then you always get the a member of the Foo base subobject.

In other words, you cannot "override" data members.

The other code you allude to only has one data member, and it would look like this:

struct Foo
{
    int a;
    Foo() : a(0) { }
protected:
    explicit Foo(int n) : a(n) { }
};

struct Bar : Foo
{
    Bar() : Foo(1) { }
};

Note how both Foo and Bar only have one single data member a in this setup.

于 2013-04-25T22:38:32.953 回答