【问题标题】:C++ How to make derived class to take base class parameters automaticallyC ++如何使派生类自动获取基类参数
【发布时间】:2020-08-31 04:01:03
【问题描述】:

当我更改基类中的值,然后创建子类的对象时,使用空参数而不是更改的值创建子类。 有没有办法用基类的参数来实现派生类的对象?

示例:

Base.h

class Base
{

class Child;

public:
    int number = 0;
    Child *chilObject;

    void Setup()
    {
         number = 5;
         childObject = new Child;
    }
};

Child.h

class Child :
    public Base
    {

    };

主要

int main()
{
    Base base;   
    base.Setup();

    cout << base.number << " : " << base->chilObject.number << endl;
    cout <<  << endl;        
}

输出:5 : 0

我只是想问是否有办法让派生类对象自动获取基类变量。

【问题讨论】:

  • 您谈论“基”类和“派生”类,但我在您的代码中看不到任何继承。
  • 即使假设Child 派生自Base,那么childObject 与其拥有的Base 实例没有直接联系。这不是你使用继承的方式
  • 这不是继承,这是组合(某种意义上的)。 class Child; 是一个与Base 没有已知关系的类的前向声明。 Child *chilObject; 声明了一个指向 Child 的指针——不是继承。
  • 我更新了问题并添加了class child,希望现在更清楚了。
  • 为什么基类甚至对子类有引用,只有子类应该对基类有引用

标签: c++ derived-class


【解决方案1】:

这是在 C++ 中的典型实现方式:

#include <iostream>

class Base
{

public:

    int number = 0;

    virtual ~Base() = default;

    void Setup()
    {
        number = 5;
    }
};

class Child : public Base
{
    // number exists here because of inheritance.
};

int main()
{
    // Child object seen as Base object:
    Base* base = new Child;
    base->Setup();

    // Child object seen as Child object:
    Child* child = static_cast< Child* >( base );

    // Both share the same 'number' variable, so:

    std::cout << base->number << " : " << child->number << std::endl;
    std::cout << std::endl;

    // Free memory taken by 'new'.
    delete base;

    return 0;
}

产量:

5 : 5

在实际代码中,您可能会将Setup 设为虚拟而不是强制转换。

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 2012-07-09
    • 2013-09-13
    • 2011-07-20
    • 2013-10-15
    • 1970-01-01
    相关资源
    最近更新 更多