c++ - 有没有办法用父类的命名空间/类空间来引用子类?

标签 c++ class inheritance namespaces c++20

假设我有以下 Mouse Event 类,其中包含一个 Button 事件并扩展了 Button PressButton Release事件:

namespace Event {
    namespace Mouse {
        class Button : public Event {
          public:
            inline Input::Code::Mouse get_mouse_button() const {
                return m_Button;
            }
    
            EVENT_CLASS_CATEGORY(Event_Category_Input | Event_Category_Mouse)
          protected:
            Button(Input::Code::Mouse button)
                : m_Button(button) {}
            Input::Code::Mouse m_Button;
        };
    
        class Press : public Button {
          public:
            Press(Input::Code::Mouse button) : Button(button) {}
    
            std::string to_string() const override {
                return fmt::format("Mouse Button Press: {0}", m_Button);
            }
    
            EVENT_CLASS_TYPE(Mouse_Button_Press)
        };
    
        class Release : public Button {
          public:
            Release(Input::Code::Mouse button)
                : Button(button) {}
    
            std::string to_string() const override {
                return fmt::format("Mouse Button Release: ", m_Button);
            }
    
            EVENT_CLASS_TYPE(Mouse_Button_Release)
        };
    }
}

我想用 Event::Mouse::Button::PressEvent::Mouse::Button::Release 来引用这些,而不是 Event::Mouse::PressEvent::Mouse::Release。我不能直接添加 namespace Button 来强制执行此行为,因为它会与已经定义的 Button 类冲突。有没有办法做到这一点?我知道我可以分别将其命名为 Button_PressButton_Release,但出于文体原因我不想这样做。提前致谢!如果不可能,我会接受它并使用下划线。

最佳答案

是的,你可以做到这一点。

转发在您的 Button 类中声明这些类型。

这为类型提供了您想要的范围。

class Button : public Event {
  public:

    class Press;
    class Release;        

};

然后,您可以在类之外定义它们。

你必须在类之外定义它们,所以父类Button是完全定义的。

class Button::Press : public Button {
public:

};

class Button::Release : public Button {
public:

};

关于c++ - 有没有办法用父类的命名空间/类空间来引用子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66071098/

相关文章:

python - 解决模板 block 结构与第三方 django 应用程序的冲突

c++ - 引用的条件分配

c++ - 我如何让 opencl 在我的 GPU 上运行

C++ 读取 LPCVOID 指针的值

python - 对象没有属性 - 类之间共享变量名

java - 使用数组调用方法时出现问题

php - PHP 中的可变变量类扩展——可能吗?

c++ - 从 C++ 中的 vector 继承类调用 super 运算符==

C++ Libssh -sever/client file transfer over the lan 例子

c# - 继承过程中的构造函数调用层次——带参数和不带参数