C++ 如何使派生类自动获取基类参数



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

例:

基数.h

class Base
{
class Child;
public:
int number = 0;
Child *chilObject;
void Setup()
{
number = 5;
childObject = new Child;
}
};

儿童.h

class Child :
public Base
{
};

主要

int main()
{
Base base;   
base.Setup();
cout << base.number << " : " << base->chilObject.number << endl;
cout <<  << endl;        
}

输出: 5 : 0

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

以下是通常在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虚拟的,而不是强制转换的。

最新更新