【问题标题】:Does a Derived Class allocate memory for the inherited variable, or it just gets access to it?派生类是否为继承的变量分配内存,或者它只是访问它?
【发布时间】:2021-10-22 16:47:17
【问题描述】:

// c++ class inheritance
#include<iostream>
using namespace std;

class A
{
public:
    int x;
};

class B: public A
{
};
int main()
{
    B b;
    b.x=5;
    cout<<b.x<<endl;

    return 0;
}

派生类是否为继承的变量分配内存,或者它只是从基类中访问它??

【问题讨论】:

    标签: c++ oop inheritance memory allocation


    【解决方案1】:

    基类实际上变成了派生类中的一个字段。几乎就像你做的那样:

    struct A {
      int i;
    };
    
    struct B {
      A __base_a;
    };
    

    所以,当您执行b.x 时,几乎就像您执行了b.__base_a.x

    这并不完全是这样,但它是一个很好的概念模型。

    【讨论】:

      【解决方案2】:

      变量的内存只分配一次。派生类只是访问它,并通过它自己的可能成员扩展基类。派生类是一个基类,加上它自己的变量。

      【讨论】:

        猜你喜欢
        • 2014-01-29
        • 2014-03-07
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-23
        • 2016-09-20
        • 1970-01-01
        相关资源
        最近更新 更多