混淆C ++继承 [英] Confused with C++ Inheritance

查看:158
本文介绍了混淆C ++继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下代码的输出感到困惑:

I'm so confused with the output of the following code:

#include <iostream>

using namespace std;

class Parent
{
public:
    Parent() : x(2) { }
    virtual ~Parent() { }

    void NonVirtual() { cout << "Parent::NonVirtual() x = " << x << endl; }

private:
    int x;
};

class Child : public Parent
{
public:
    Child() : x(1) { }
    virtual ~Child() { }

    void NonVirtual() { cout << "Child::NonVirtual() x = " << x << endl; }

private:
    int x;
};

int main()
{
    Child c;
    Parent* p = &c;

    c.NonVirtual();  // Output: Child::NonVirtual() x = 1
    p->NonVirtual(); // Output: Parent::NonVirtual() x = 2
    // Question: are there two x'es in the Child object c?
    //           where is x = 2 from (we have not defined any Parent object)?

    cout << sizeof(c) << endl;
    cout << sizeof(*p) << endl;

    return 0;
}


推荐答案

在C ++中,只有标记为 virtual 的函数是 overriden 。你在这里是阴影,而不是凌驾。在覆盖和继承中,行为基于运行时类型,这是您期望的正常继承行为,但如果您不声明它为virtual,则该行为纯粹基于时间类型(即声明类型)。因为p声明为Parent *类型,所以它使用Parent中的实现,而c声明为Child类型,因此它使用Child类型给出的版本。如果你声明了方法virtual,那么在这两种情况下,它都会在运行时查找函数的相应版本,并调用Child类中给出的版本。

The code above illustrates the fact that, in C++, only functions marked virtual are overriden. What you have here is overshadowing, not overriding. In overriding and inheritance, the behavior is based on runtime type which is the normal inheritance behavior you expect, but if you don't declare it virtual, then the behavior is based purely on compile-time type (i.e. declared type). Since p is declared to be of type Parent* it uses the implementation in Parent, while c is declared to be of type Child, and so it uses the version given by type Child. If you declared the method virtual, then in both cases, it would lookup the appropriate version of the function at runtime and invoke the version given in the Child class.

还要补充说,你有两个不同的x变量...如果你想在基类和派生类之间共享变量,你应该在基类中标记为protected(虽然我认为它通常设计不好这样做)。您在Child中声明的x变量是与Parent中的变量不同的变量。请记住,x在Parent中是私有的,所以x在Child中没有任何意义,直到你在Child中创建了一个名为x的第二个变量。

I should also add that you have two different x variables... if you want to share variables between a base class and a derived class, you should mark it "protected" in the base class (although I would argue that it is generally poor design to do so). The x variable that you declare in Child is a different variable from the one in Parent. Remember that x is private in Parent, and so the name x didn't have any meaning in Child until you created a second variable named x in Child.

这篇关于混淆C ++继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆