c++ - `&ClassName::function` 的调用方法代表什么?
问题描述
connect( &objTwo, &Two::emitThisSignal, this, &Controller::mySlot );
这里的二是一个单独的类。它的对象已在 Controller 类中创建。它的信号必须连接到控制器类的插槽。
连接的签名是:
connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
connect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type) const
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)
connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type)
我的连接调用代表上面的哪个签名?
为什么我不能简单地写:connect( &objTwo, objTwo.emitThisSignal, this, this->mySlot );
?
解决方案
我的连接调用代表上面的哪个签名?
这个:
connect(const QObject *sender, PointerToMemberFunction signal,
const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)
最后一个参数是 default( Qt::ConnectionType type = Qt::AutoConnection
),因此您没有明确指定它。链接到文档
为什么我不能简单地写:
connect( &objTwo, objTwo.emitThisSignal, this, this->mySlot );?
因为如果你想传递一个指向成员函数的指针,那是无效的 C++ 语法。objTwo.emitThisSignal
在 C++ 语法中意味着,访问内部的数据成员,而函数需要一个指向成员函数的指针。emitThisSignal
objTwo
但是,如果你写:
connect( &objTwo, SIGNAL(objTwo.emitThisSignal), this, SLOT(this->mySlot) );
您的代码可能会编译,但不会按预期工作。其原因可以通过查看第一个connect
签名来理解:
connect(const QObject *sender, const char *signal,
const QObject *receiver, const char *method, Qt::ConnectionType type)
它将指针char*
作为第二个和第四个参数。所以任何语法都会被编译。宏SIGNAL()
并将SLOT()
它们转换为字符串,然后 Qt 在运行时使用它们在发出信号时调用正确的插槽。上述语法甚至可能不会导致崩溃或任何警告。我知道这听起来很可怕,但这就是 Qt 5 出现之前 Qt 的状态。
这些天来,强烈建议您使用这三个签名:
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)
connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type)
推荐阅读
- c# - 使用 Asp.net 应用程序中的 WCF SOAP 服务时出错(没有端点监听)
- java - JPA:两端都有列表而没有无限循环
- java - weblogic.xml.crypto.wss.WSSecurityException:时间戳验证失败
- docker - 带有 docker 的 k8s 使用 env 变量
- swift - 如何在 React Native 或 Swift 中实现 IG TV 底部滑动面板?
- bash - 遍历关联数组并在内容上发送一封邮件
- reactjs - 为什么我不能将一个 MERN 堆栈项目完全上传到 Github?(在别处找不到解决方案)
- angularjs - 角度日期显示格式
- sql-server - SQL Server VB.NET 的更新查询
- node.js - nodejs中TypeORM的实现