简体   繁体   English

如何在C ++中通过类结构共享代码?

[英]How do I share code via class structure in C++?

I am writing for the Qt framework and I want to create a QWidget. 我正在写Qt框架,我想创建一个QWidget。 QWidget exposes some interfaces such as mousePressEvent and mouseReleaseEvent. QWidget公开了一些接口,例如mousePressEvent和mouseReleaseEvent。 I want to extend this class to allow mouseClickEvent and mouseDoubleClickEvent. 我想扩展此类,以允许mouseClickEvent和mouseDoubleClickEvent。 Normally, you would think to extend QWidget and implement those functions. 通常,您会考虑扩展QWidget并实现这些功能。 The problem is that there are other classes (QPushButton for example) provided as part of the library which extend QWidget. 问题是作为库的一部分提供了其他类(例如QPushButton),这些类扩展了QWidget。 Therefore, how do I get that added functionality into those classes without having to extend each one and copy the code? 因此,如何在不扩展每个类和复制代码的情况下,将添加的功能添加到这些类中?


class ClickHandeler : public QWidget {
    virtual void mouseClickEvent();
    virtual void mouseDoubleClickEvent();

    int clickCount; //initialized to 0;

    void mouseReleaseEvent(QEvent *event){
        clickCount++;
        QTimer::singleShot(500, this, SLOT(checkClick()));
    }

    void checkClick(){
        if (clickCount == 2){
            this->mouseDoubleClickEvent();
            clickCount = clickCount-2;
        } else {
            this->mouseDoubleEvent()
            clickCount--;
        }
    }
}

// QPushButton inherits QWidget too! Yikes!
class MyPushButton : public QPushButton, public ClickHandeler {
    void mouseClickEvent(){
        alert("i have been clicked");
    }

    void mouseDoubleClickEvent(){
        alert("i have been double clicked");
    }
}

I want something like MyPushButton, but I am worried that the function overriding will not work as expected. 我想要类似MyPushButton之类的东西,但是我担心该函数替代无法按预期工作。

Im sorry if this question is obvious to people, but I do not know what the terminology is. 很抱歉,这个问题对人们来说是显而易见的,但是我不知道该用什么术语。 I have googled interfaces for c++ and I get abstract interfaces (which doesnt properly solve this problem). 我有谷歌接口的C ++,我得到抽象接口(不能正确解决此问题)。 If I'm just being stupid and need to know a better term for google, let me know in the comments and Ill remove the question. 如果我只是个愚蠢的人,需要了解Google更好的用语,请在评论中让我知道,然后我将删除问题。

I think you just need to extend the QWidget and call the QWidget same functions. 我认为您只需要扩展QWidget并调用QWidget相同的功能即可。 For example: 例如:

class QWidget {
public:
    void mouseClickEvent();
};

class QPushButton {
public:
    void mouseClickEvent();
};

class MyWidget : public QWidget, public QPushButton {
public:
    void mouseClickEvent()
    {
        //base::mouseClickEvent();// ambiguous
        QWidget::mouseClickEvent();
        QPushButton::mouseClickEvent();
        /* Do your own code here */
    }
};

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

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