[英]How to access derived class fields using polymorphism in c++?
i have a simple parameter model class which derives from the base class, like this:我有一个派生自基类的简单参数模型类,如下所示:
class IParams
{
....
};
class QEParams : public IParams
{
....
};
I also have executor class which derives from the base class containing IParams field.我还有从包含 IParams 字段的基类派生的 executor 类。
class IExecutor
{
protected:
IParams parameters;
public:
virtual inline void initialize(IParams parameters) = 0;
virtual IParams& execute() = 0;
};
class QEExec : public IExecutor
{
public:
virtual void initialize(IParams parameters) override;
virtual QEParams& execute() override;
};
Class QEExec should hold QEParams in parameters field.类 QEEExec 应该在参数字段中保存 QEParams。 How to access QEParams members in QEExec class?
如何访问 QEEExec 类中的 QEParams 成员? Should I cast the type of parameters to QEParams?
我应该将参数类型转换为 QEParams 吗?
While I agree, that you should probably overthink your design, here is how you do what you want to do:虽然我同意,您可能应该过度考虑您的设计,但您可以按照以下方式做您想做的事情:
If you want parameters
to be able to house either an object of type IParams
and of type QEParams
the standard way to do this, is to use a pointer or parameter to base class.如果您希望
parameters
能够容纳IParams
类型和QEParams
类型的对象, IParams
执行此QEParams
的标准方法是使用指向基类的指针或参数。 You cannot let parameters
have type IParams
and expect it to fit also an object of type QEParams
since those two have a different memory layout (and probably a different size) so they necessarily cannot be at the same place.您不能让
parameters
具有IParams
类型并期望它也适合QEParams
类型的对象,因为这两个具有不同的内存布局(并且可能具有不同的大小),因此它们必然不能在同一位置。
It depends a bit on the structure of your code, how exactly you want to do this.这在一定程度上取决于您的代码结构,以及您想要如何执行此操作。 If the Executor owns the parameter, the best type would be
std::unique_ptr<IParams>
.如果 Executor 拥有参数,最好的类型是
std::unique_ptr<IParams>
。 Otherwise you probably want to use either IParams*
, IParams&
or std::shared_ptr<IParams>
depending on how you manage the lifetime of this object.否则,您可能想要使用
IParams*
、 IParams&
或std::shared_ptr<IParams>
具体取决于您如何管理此对象的生命周期。 The argument to initialize should be of the same type (and use move semantics if your working with std::unique_ptr
).初始化的参数应该是相同的类型(如果您使用
std::unique_ptr
,请使用移动语义)。
To access QEParams
' members, you have to use dynamic_cast
.要访问
QEParams
的成员,您必须使用dynamic_cast
。 But be very careful with this.但要非常小心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.