Tips:
参数重载时需要函数指针明确重载的是哪一个,避免出现二义性
案例修改:
重载学生类中的treat函数,增加foodName参数
//Teacher.h
#ifndef TEACHER_H
#define TEACHER_H
#include <QObject>
class Teacher : public QObject
{
Q_OBJECT
public:
explicit Teacher(QObject *parent = 0);
//自定义信号 写到signals下
//1:返回值是woid
//2:只需要声明,不需要实现
//3:可以有参数,可以发生重载
signals:
void hungry();
void hungry(QString foodName);
public slots:
};
#endif // TEACHER_H
//Student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <QObject>
class Student : public QObject
{
Q_OBJECT
public:
explicit Student(QObject *parent = 0);
signals:
//槽函数写在public solts下,或者public下,或者全局函数,lambda
// 返回值为void
// 需要声明,需要实现
// 可以有参数,可以重载
public slots:
void treat();
void treat(QString foodName);
};
#endif // STUDENT_H
//Student.cpp
#include "student.h"
#include "QDebug"
Student::Student(QObject *parent) : QObject(parent)
{
}
void Student::treat(){
qDebug()<<"请老师吃饭";
}
void Student::treat(QString foodName){
qDebug()<<"请老师吃饭,老师要吃:"<<foodName;
}
//widget.cpp
#include "widget.h"
//Teacher老师类 Student 学生类
//下课,老师发送饿了的信号,学生响应信号,请老师吃饭
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
//加this则不需要手动delete
this->zt = new Teacher(this);
this->st = new Student(this);
// 连接信号和槽
// connect(this->zt,&Teacher::hungry,this->st,&Student::treat);
//连接有参的信号和槽
//函数指针 指向 函数地址
void (Teacher:: * teacherSignal)(QString) = &Teacher::hungry;
void (Student:: *studentSlot)(QString) = &Student::treat;
connect(this->zt,teacherSignal,this->st,studentSlot);
//下课函数调用
classOver();
}
void Widget::classOver(){
//触发自定义信号
emit this->zt->hungry();
//触发有参信号
emit this->zt->hungry("宫保鸡丁");
}
Widget::~Widget()
{
}
运行结果:QString默认加双引号
如果想要去掉双引号,需要将QString转换为char*
void Student::treat(QString foodName){
//QSTring 转为char*
//先调用toUtf-8 转为QByteArray
//再调用data转为char*
qDebug()<<"请老师吃饭,老师要吃:"<<foodName.toUtf8().data();
}