简体   繁体   English

C ++继承和成员访问问题

[英]C++ inheritance and member access issues

I am learning about OOP with c++ and have run into a situation I don't quite understand. 我正在学习C ++的OOP,遇到了一种我不太了解的情况。

{Understanding the poor practice of public data members and assuming pointers are not NULL}: {了解公共数据成员的不良做法并假定指针不为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;
}

And after a little more tinkering I found that if I instead use constructors to set non const int a values to 0 and 1 respectively AND also output the value form the constructor I see that the value is in fact being set to 1 in BAR, but being evaluated as 0 inside the display function. 再经过一番修改后,我发现如果我改用构造函数分别将non const int的值设置为0和1并从构造函数中输出该值,我会发现实际上该值在BAR中被设置为1,但是在显示函数中被评估为0。

I am sorry if this does not make sense, I doubt I really understand well enough to ask the right question, but I am wondering why BAR is not treated like a Bar inside display and how to get it to do so (if possible while still using the base class pointer as an argument). 抱歉,如果这样做没有道理,我怀疑我是否真的理解得足够清楚,可以提出正确的问题,但是我想知道为什么BAR不能像显示器中的Bar一样对待,以及如何做到这一点(如果可能,尽管仍然可以)使用基类指针作为参数)。

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. 您的Bar类有两个名为a成员,一个是Bar::a ,一个是Bar::Foo::a ,它是Foo基类的成员。

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. 当通过指针访问FooBar对象(如p->a始终会获得Foo基础子对象a成员。

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. 注意两者如何FooBar只有一个单一的数据成员a在此设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM