【问题标题】:Add functionality to class and all of it's subclasses向类及其所有子类添加功能
【发布时间】:2013-07-01 12:38:57
【问题描述】:

我有 3 个类继承自 3 个不同的类,这些类都继承自 QWidget 基类。 例如:

  1. MyMainWindow : public QMainWindow : public QWidget
  2. MyPushButton : public QPushButton : public QWidget
  3. MyTextEdit : public QTextEdit : public QWidget

我最终会有更多这样的课程。 我现在想做的是为我的所有类添加一个通用方法;这意味着它应该被添加到QWidget 基类中,但我无法编辑它(我宁愿不为一种方法更改 Qt 源代码)。

这种行为可能吗? 我已经尝试过使用这样的接口:

class MyTextEdit : public QTextEdit, IMyMethodContainer { ... };

但问题是,我需要在IMyMethodContainer 中访问QObject::connect(sender, signal, this, slot);,而通过this 我试图访问MyTextEdit,而不是IMyMethodContainer,它不是@987654332 的子类@。

【问题讨论】:

    标签: c++ qt oop inheritance methods


    【解决方案1】:

    CRTP 可能会有所帮助。

    template<typename Derived, typename Base>
    struct InjectMethod: Base {
      static_assert( std::is_base_of< InjectMethod<Derived,Base>, Derived >::value, "CRTP violation" );
      Derived* self() { return static_cast<Derived*>(this); }
      Derived const* self() const { return static_cast<Derived*>(this); }
      void my_method() {
        // use self() inside this method to access your Derived state
      }
    };
    

    然后:

    class MyTextEdit: InjectMethod< MyTextEdit, QTextEdit > {
    };
    class MyPushButton: InjectMethod< MyPushButton, QPushButton > {
    };
    

    InjectMethod&lt; MyTextEdit, QTextEdit &gt; 内部,您可以访问self() 指针,该指针可以访问MyTextEditInjectMethod&lt; MyPushButton, QPushButton &gt; 内部的所有内容。

    您可能不需要Derived 部分——如果您只使用QWidget 功能,可能只有一个模板参数(您的基础)就足够了。

    【讨论】:

    • 谢谢你,救命恩人 :) 是的,我不会使用Derived 部分,但请保留它,其他人可能需要它^^
    【解决方案2】:

    在 Java 中,您可以“扩展” QWidget 并在其中添加自定义方法。

    Class MyQWidgetExtension extends QWidget { ... }
    

    您的其他类(QMainWindow、QpushButton、QtextEdit)只是从那里扩展(“继承”)。 C++有类似的吗?

    Class MyQWidgetExtension : public QWidget { ... }
    

    【讨论】:

    • 问题是QTextObject,他也无法控制QWidget 和@Markus 的类。
    猜你喜欢
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多