简体   繁体   English

QObject的多重继承

[英]Multiple inheritance of QObject

I have a class that would listen via connect to some signals in a couple of different contexts, and a dialog that would do said listening among other things. 我有一个可以在几个不同上下文中通过连接到某些信号进行侦听的类,以及一个可以进行侦听的对话框。

class MyListener : public QObject
{
    Q_OBJECT
};

class MyDialog : public QDialog, public MyListener
{
    Q_OBJECT
};

That caused the following compilation error: 这导致以下编译错误:

error: reference to 'connect' is ambiguous 错误:对“连接”的引用不明确

I suspected that may be caused by multiple inheritance of QObject by MyDialog, once via QDialog and once via MyListener. 我怀疑这可能是由于MyDialog对QObject的多重继承所致,一次是通过QDialog,一次是通过MyListener。 However, making all the above inheritance statements virtual didn't eliminate the error. 但是,将所有上述继承语句设为虚拟并不能消除该错误。

Could you suggest what may be the cause of this? 你能建议这是什么原因吗?

Make it: 做了:

class MyDialog : public QDialog
{
    Q_OBJECT

    public:
    MyListener& listener() { return m_listener; }

    private:
    MyListener m_listener;
};

Have you considered inheriting your QObject as protected instead? 您是否考虑过将QObject继承为受保护对象? This is because both classes use the connect() function to connect slots and signals together in your .ui file, having each class inherit each other means you now have two possible connect functions whenever the program makes a call to connect your signal/slots 这是因为两个类都使用connect()函数将.ui文件中的插槽和信号连接在一起,使每个类相互继承意味着现在只要程序调用连接信号/插槽,您就有两个可能的connect函数。

have your needed functions under protected and prevent the ambiguity of two connect() 使所需的功能受到保护,并防止两个connect()的歧义

class MyListener
{
    public:
        //...
    protected:
        int a;
        //stuff to share
};

class MyDialog: public QDialog, protected MyListener 
{

    //has access to all protected members but not the private members
};

making all the above inheritance statements virtual didn't eliminate the error. 将所有上述继承语句设为虚拟并不能消除该错误。

This is expected, as the virtual keyword only affects the immediate base class. 这是预期的,因为virtual关键字仅影响直接基类。 That is, MyListener still inherits QObject non-virtually. 也就是说, MyListener仍然非虚拟地继承QObject You cannot really change that. 您无法真正改变它。

On top of that, the documentation says 最重要的是,文档说

Virtual inheritance with QObject is not supported. 支持使用QObject进行虚拟继承。

The only reasonable solution is to have MyListener not inherit QObject . 唯一合理的解决方案是让MyListener 继承QObject

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

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