使用qDebug打印自定义类型

本文介绍了如何在Qt环境中,通过定义流操作函数并将其声明为自定义类型Message的友元,来实现使用qDebug()函数打印自定义类型Message的私有成员,从而方便调试代码。
摘要由CSDN通过智能技术生成

使用qDebug打印自定义类型

本文主要介绍如何使用qDebug()打印自定义类型,关于自定义类型的创建,请参考:

编写自定义Qt类型

打印自定义类型:

我们在调试代码时,经常使用qDebug()进行信息打印

Message message(body, headers);
qDebug() << "Original:" << message;

为了让自定义类型Message实现此功能,需要创建一个流操作函数

QDebug operator<<(QDebug dbg, const Message &message);

下面是这个函数的具体实现:

QDebug operator<<(QDebug dbg, const Message &message)
{
 const QString body = message.body();
 QVector<QStringRef> pieces = body.splitRef("\r\n", QString::SkipEmptyParts);
 if (pieces.isEmpty())
     dbg.nospace() << "Message()";
 else if (pieces.size() == 1)
     dbg.nospace() << "Message(" << pieces.first() << "
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用自定义类型的泛型类的示例代码,包含.h和.cpp文件: SP104.h ```cpp #ifndef SP104_H #define SP104_H #include <QtCore> struct SP104 { quint8 addr0; quint8 addr1; quint8 addr2; }; Q_DECLARE_METATYPE(SP104) #endif // SP104_H ``` DP104.h ```cpp #ifndef DP104_H #define DP104_H #include <QtCore> struct DP104 { quint8 addr0; quint8 addr1; quint8 addr2; QString data; }; Q_DECLARE_METATYPE(DP104) #endif // DP104_H ``` GenericPrinter.h ```cpp #ifndef GENERICPRINTER_H #define GENERICPRINTER_H #include <QtCore> template<typename T> class GenericPrinter { public: static void print(const T& value) { int type = qMetaTypeId<T>(); if (type == qMetaTypeId<SP104>()) { const SP104& sp = static_cast<const SP104&>(value); qDebug() << "SP104: " << sp.addr0 << ", " << sp.addr1 << ", " << sp.addr2; } else if (type == qMetaTypeId<DP104>()) { const DP104& dp = static_cast<const DP104&>(value); qDebug() << "DP104: " << dp.addr0 << ", " << dp.addr1 << ", " << dp.addr2 << ", " << dp.data; } else { qDebug() << "Unknown type"; } } }; #endif // GENERICPRINTER_H ``` main.cpp ```cpp #include <QtCore> #include "SP104.h" #include "DP104.h" #include "GenericPrinter.h" int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); SP104 sp = {0x01, 0x02, 0x03}; DP104 dp = {0x04, 0x05, 0x06, "Hello, world!"}; GenericPrinter<SP104>::print(sp); GenericPrinter<DP104>::print(dp); return app.exec(); } ``` 在这个示例中,我们使用Q_DECLARE_METATYPE宏声明了SP104和DP104类型为元类型,这样我们就可以使用qMetaTypeId函数获取它们的类型ID。在GenericPrinter类中,我们使用qMetaTypeId函数获取传递给print函数的值的类型ID,并根据类型ID打印不同的数据。在main函数中,我们创建了一个SP104类型的变量和一个DP104类型的变量,并将它们传递给GenericPrinter类的print函数进行打印
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值