如何重载运算符<<对于qDebug

时间:2010-04-20 18:17:51

标签: c++ qt4 operator-overloading

我正在尝试为我的类存储数据创建更有用的调试消息。我的代码看起来像这样

#include <QAbstractTableModel>
#include <QDebug>

/**
  * Model for storing data. 
  */
class DataModel : public QAbstractTableModel {
    // for debugging purposes
    friend QDebug operator<< (QDebug d, const DataModel &model);

    //other stuff
};

/**
  * Overloading operator for debugging purposes
  */
QDebug operator<< (QDebug d, const DataModel &model) {
    d << "Hello world!";
    return d;
}

我希望qDebug() << model能打印出“Hello world!”。但是,输出总是有“QAbstractTableModel(0x1c7e520)”。

你知道什么是错的吗?

5 个答案:

答案 0 :(得分:20)

我现在知道很久了,但只是为了记录并帮助其他最终来到这里的人有同样的疑问,最简单的方法来获得qDebug()&lt;&lt;使用自己的类打印类似“Hello World”或其他任何内容的方法是实现类的隐式转换为可打印类型,如QString(QDebug很好地支持)。

class Foo {
public:
   Foo() { }
   operator QString() const { return <put your QString here>; }   

};

答案 1 :(得分:12)

在玩了这个问题一小时后,我发现model是指向DataModel的指针,而我的运算符<<只接受引用。

答案 2 :(得分:8)

在您的示例中,qDebug()打印变量的地址,这是未知类型的默认行为。

事实上,你似乎有两件事需要照顾:

  • 按值获取项目(eugen已经指出了它!)。
  • 在使用之前定义重载运算符,将其签名放在头文件中,或者在使用之前将其定义为forward(否则您将获得默认的“qDebug()&lt;&lt;”行为)。

这会给你:

QDebug operator<< (QDebug d, const DataModel &model) {
    d << "Hello world!";
    return d;
}
DataModel m;
qDebug() << "m" << m;

QDebug operator<< (QDebug d, const DataModel &model);

DataModel m;
qDebug() << "m" << m;

QDebug operator<< (QDebug d, const DataModel &model) {
    d << "Hello world!";
    return d;
}

我也很难学到它......

答案 3 :(得分:3)

我在 raven-worx 的QT论坛上找到this answer(在信用到期的情况下给予信用!)

.h文件中:

QDebug operator<<(QDebug dbg, const MyType &type);

其中MyType是您的类,例如DataModeltype是您要显示的实例。

.cpp文件中:

QDebug operator<<(QDebug dbg, const MyType &type)
{
    dbg.nospace() << "MyType(" << .... << ")";
    return dbg.maybeSpace();
}

您可以使用QDebug的space()nospace()和其他方法来控制流的准确显示。

因此,对于OP,我们将使用:

// in the .h file:
class DataModel : public QAbstractTableModel {
// stuff
};
QDebug operator<<(QDebug dbg, const DataModel &data);

// in the .cpp file:
QDebug operator<<(QDebug dbg, const DataModel &data)
{
    dbg.nospace() << "My data {" << data.someField << ',' << data.another << "}";
    return dbg.maybeSpace();
}

// in some .cpp user of the class:
DataModel myData;

. . .

QDebug() << "The current value of myData is" << myData;

答案 4 :(得分:2)

您仅实施了&lt;&lt;运营商参考。如果您的model变量是指针,它将使用另一个实现(不是您的)。

要使用您的实施,您可以:

qDebug() << *model

顺便说一句,实现QDebug operator<<(QDebug dbg, const T &data)重载的正确方法是使用QDebugStateSaver类:

QDebug operator<<(QDebug dbg, const QDataflowModelOutlet &outlet)
{
    QDebugStateSaver stateSaver(dbg);
    dbg.nospace() << ...;
    return dbg;
}

这样,退出该功能时,将正确恢复设置(即插入或不打印空间)。