繁体   English   中英

如何使虚函数接受仅在派生类中定义的数据类型?

[英]How to make a virtual function accept a data type defined only in derived classes?

我有一个带有两个虚函数的 C++ 类,它们使用未定义的State结构作为返回/参数类型。 我的问题是State结构仅在派生类中定义,而基类对此一无所知。

class Base {
    // Error: Identifier 'State' is undefined
    virtual void serialize(State& last_state) = 0;
    virtual State& getCurrentState() = 0;
};

class Derived : public Base {
    struct State { // Every derived class has different State fields
        int32_t x = 0;
        int32_t y = 0;
    } current_state;
    void serialize(State& last_state) override;
    State& getCurrentState() override;
}

虚拟数据成员不是一回事,所以我假设我不能定义一个结构两次。 我还想过,也许我可以创建一个空的基础结构,并让每个派生类的 State 都继承自它,但这似乎不是一个非常干净的解决方案。

如果有一个完全不同的方式可以解决这个问题,我正在尝试做的一些背景:

我有一个从 Base 继承的对象映射( std::unordered_map<int, std::shared_ptr<Entity> )。 我有时会遍历地图并希望为每个对象调用serialize()getCurrentState()
我不知道我正在访问哪个派生对象,所以我不能只是将基指针转换为派生对象。 我不能只通过基指针调用派生类的成员,那我该怎么办?

虚拟数据成员不是一回事,所以我假设我不能定义一个结构两次。 我还想过,也许我可以创建一个空的基础结构,并让每个派生类的 State 都继承自它,但这似乎不是一个非常干净的解决方案。

这确实是你应该做的。 我认为它更干净,当你在Base中将基状态声明为受保护的类时,所以

class Base {
protected:
    struct State{};
public:
    virtual void serialize(State& last_state) = 0;
    virtual State& getCurrentState() = 0;
};

class Derived : public Base {
public:
    struct State : Base::State { // Every derived class has different State fields
        int32_t x = 0;
        int32_t y = 0;
    } current_state;
    void serialize(Base::State& last_state) override; // Note that the Base:: is important, otherwise the function does not override
    State& getCurrentState() override; // You can add Base:: to the return type but you don't have to.
};

暂无
暂无

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

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