C++ Qt“私人插槽:”这是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9147636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:23:08  来源:igfitidea点击:

Qt "private slots:" what is this?

c++qtsignals-slots

提问by Justin

I understand how to use it, but the syntax of it bothers me. What is "private slots:" doing?

我知道如何使用它,但它的语法让我很困扰。“私人插槽:”在做什么?

I have never seen something between the private keyword and the : in a class definition before. Is there some fancy C++ magic going on here?

我以前从未在类定义中看到 private 关键字和 : 之间的东西。这里有什么奇特的 C++ 魔法吗?

And example here:

和这里的例子:

 #include <QObject>

 class Counter : public QObject
 {
     Q_OBJECT

 public:
     Counter() { m_value = 0; }

     int value() const { return m_value; }

 public slots:
     void setValue(int value);

 ...

采纳答案by Russell Davis

Slots are a Qt-specific extension of C++. It only compiles after sending the code through Qt's preprocessor, the Meta-Object Compiler (moc). See http://doc.qt.io/qt-5/moc.htmlfor documentation.

Slots 是 C++ 的 Qt 特定扩展。它仅在通过 Qt 的预处理器元对象编译器 (moc) 发送代码后才进行编译。有关文档,请参阅http://doc.qt.io/qt-5/moc.html

Edit: As Frank points out, moc is only required for linking. The extra keywords are #defined away with the standard preprocessor.

编辑:正如弗兰克指出的,只有链接才需要 moc。额外的关键字与标准预处理器一起#defined。

回答by Andrew

The keywords such as public, privateare ignored for Qt slots. All slots are actually public and can be connected

Qt 插槽会忽略诸如public, 之private类的关键字。所有插槽实际上都是公共的,可以连接

回答by Euri Pinhollow

Declaring slots as private means that you won't be able to reference them from context in which they are private, like any other method. Consequently you won't be able to pass private slots address to connect.

将插槽声明为私有意味着您将无法像任何其他方法一样从它们私有的上下文中引用它们。因此,您将无法将私有插槽地址传递给connect.

If you declare signal as private you are saying that only this class can manage it but function member pointers do not have access restrictions:

如果将信号声明为私有,则表示只有此类可以管理它,但函数成员指针没有访问限制

class A{
    private:
    void e(){

    }
    public:
    auto getPointer(){
        return &A::e;   
    }
};

int main()
{
    A a;
    auto P=a.getPointer();
    (a.*P)();
}

Other than that, what other answers mention is valid too:
- you still can connect private signals and slots from outside with tricks
- signalsand slotsare empty macros and do not break language standard

除此之外,其他答案提到的也是有效的:
-您仍然可以使用技巧从外部连接私人信号和插槽
-signals并且slots是空宏并且不会违反语言标准