在 QT 中重载 QDebug
Overloading QDebug in QT
在 view.h 文件中:
friend QDebug operator<< (QDebug , const Model_Personal_Info &);
在 view.cpp 文件中:
QDebug operator<< (QDebug out, const Model_Personal_Info &personalInfo) {
out << "Personal Info :\n";
return out;
}
调用后:
qDebug() << personalInfo;
假设输出:"Personal Info :"
但出现错误:
error: no match for 'operator<<' in 'qDebug()() << personalInfo'
Header:
class DebugClass : public QObject
{
Q_OBJECT
public:
explicit DebugClass(QObject *parent = 0);
int x;
};
QDebug operator<< (QDebug , const DebugClass &);
并实现:
DebugClass::DebugClass(QObject *parent) : QObject(parent)
{
x = 5;
}
QDebug operator<<(QDebug dbg, const DebugClass &info)
{
dbg.nospace() << "This is x: " << info.x;
return dbg.maybeSpace();
}
或者您可以像这样在 header 中定义所有内容:
class DebugClass : public QObject
{
Q_OBJECT
public:
explicit DebugClass(QObject *parent = 0);
friend QDebug operator<< (QDebug dbg, const DebugClass &info){
dbg.nospace() << "This is x: " <<info.x;
return dbg.maybeSpace();
}
private:
int x;
};
适合我。
尽管当前的答案可以解决问题,但其中有很多代码是多余的。只需将其添加到您的 .h
.
QDebug operator <<(QDebug debug, const ObjectClassName& object);
然后在你的 .cpp
.
中像这样实现
QDebug operator <<(QDebug debug, const ObjectClassName& object)
{
// Any stuff you want done to the debug stream happens here.
return debug;
}
在 view.h 文件中:
friend QDebug operator<< (QDebug , const Model_Personal_Info &);
在 view.cpp 文件中:
QDebug operator<< (QDebug out, const Model_Personal_Info &personalInfo) {
out << "Personal Info :\n";
return out;
}
调用后:
qDebug() << personalInfo;
假设输出:"Personal Info :"
但出现错误:
error: no match for 'operator<<' in 'qDebug()() << personalInfo'
Header:
class DebugClass : public QObject
{
Q_OBJECT
public:
explicit DebugClass(QObject *parent = 0);
int x;
};
QDebug operator<< (QDebug , const DebugClass &);
并实现:
DebugClass::DebugClass(QObject *parent) : QObject(parent)
{
x = 5;
}
QDebug operator<<(QDebug dbg, const DebugClass &info)
{
dbg.nospace() << "This is x: " << info.x;
return dbg.maybeSpace();
}
或者您可以像这样在 header 中定义所有内容:
class DebugClass : public QObject
{
Q_OBJECT
public:
explicit DebugClass(QObject *parent = 0);
friend QDebug operator<< (QDebug dbg, const DebugClass &info){
dbg.nospace() << "This is x: " <<info.x;
return dbg.maybeSpace();
}
private:
int x;
};
适合我。
尽管当前的答案可以解决问题,但其中有很多代码是多余的。只需将其添加到您的 .h
.
QDebug operator <<(QDebug debug, const ObjectClassName& object);
然后在你的 .cpp
.
QDebug operator <<(QDebug debug, const ObjectClassName& object)
{
// Any stuff you want done to the debug stream happens here.
return debug;
}