这是什么?

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

我以前从未在类定义中看到过 private 关键字和: 之间的内容。这里面是不是有什么奇妙的 C + + 魔法?

举个例子:

 #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);


...
52621 次浏览

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

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.html for documentation.

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

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.

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
- signals and slots are empty macros and do not break language standard