简体   繁体   English

C ++如何使用派生对象中的独立基础对象

[英]C++ How to use stand-alone base object from derived object

I have 3 classes. 我有3节课。 One is a base, one is a parent and one is a child. 一个是基础,一个是父母,一个是孩子。 The parent is instantiated at some point and assigned data. 在某些时候实例化父对象并分配数据。 In some cases it is used directly but in others there is a need for functionality implemented in its child class. 在某些情况下,可以直接使用它,但在其他情况下,则需要在其子类中实现的功能。

What I would like to do is to cast the parent object into child object so its virtual functions would be used with parent's data: 我想做的是将父对象转换为子对象,以便将其虚拟函数与父对象的数据一起使用:

class UndoBase : public QUndoCommand
{
public:
    UndoBase() {}    

    virtual void undo() = 0;
    virtual void redo() = 0;
};

class CommandParent : public UndoBase
{
public:
    CommandParent() {}

    virtual void undo()
    virtual void redo()

protected:
    someType data
};

class CommandChild : public CommandParent
{
public:
    CommandChild() {}

    virtual void undo() //overrides parent
    virtual void redo() //overrides parent
};

I have tried this: 我已经试过了:

CommandParent *parent = new CommandParent;
//assign data
UndoBase *command = static_cast<CommandChild*>(parent);
command->redo();

And it worked (used the CommandChild implementation and CommandParent data) although I would swear it should be undefined behaviour (that could work too, I know). 它确实起作用(使用CommandChild实现和CommandParent数据),尽管我发誓它应该是未定义的行为(我知道也可以起作用)。 Since I doubt this is the right thing to do I would like to ask if this is ok or if there is other ways beside composition. 因为我怀疑这是正确的做法,所以我想问一下这是否可以,或者除构图之外还有其他方法。

UndoBase *command = static_cast<CommandChild*>(parent);

This is all hell at every inch of this line. 这条线的每一寸都是地狱。 You are telling to static_cast to cast to CommandChild whereas you are storing it in UndoBase . 您正在告诉static_cast强制转换为CommandChild,而您将其存储在UndoBase中。

Also you are trying to cast CommandParent to CommandChild means Base to Derived where Base class has no knowledge of derived cast. 另外,您还尝试将CommandParent强制转换为CommandChild,这意味着Base到Derived,而Base类不知道派生强制转换。 Even if you write it properly. 即使您正确编写它。

CommandChild  *child = static_cast<CommandChild*>(parent);

it would be erroneous.Apart from that always use dynamic_cast for these cases. 除此以外,在这些情况下请始终使用dynamic_cast。 It explicitly checks whether cast is possible or not.dynamic_cast will cast properly if cast is safe OR returns NULL (in case of pointers, for references it throws bad_cast exception ) if its not able to cast to target type. 它显式检查是否可以进行强制类型转换。如果强制类型转换是安全的,则dynamic_cast将正确地进行强制类型转换;如果无法将其强制类型转换为目标类型,则返回NULL(对于指针而言,对于引用它会抛出bad_cast异常)。

您必须使用复制构造函数使用CommandParent中的数据创建CommandChild的新实例。

UndoBase *command = new CommandChild(*parent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM