如何将指针值转换为QString?
出于调试目的,我经常将指针值(主要是 this
)输出到 qDebug:
qDebug("pointer of current object = 0x%08x",this);
,使用 "%08x " 作为格式字符串并简单地将 this
作为参数传递。
如何将指针值转换为 QString?
这是我到目前为止得到的:
char p = (char)this;
return QString("0x%1").arg(p, 8, '0');
但编译器似乎不知道如何处理该值。在这种情况下,转换为 char
是否正确?或者什么是更安全的方法来做到这一点?
使用 Visual C++ 和 Qt 4.7.4。
编辑
按照建议使用qulonglong
qulonglong p = (qulonglong)this;
return QString("0x%1").arg(p, 8, '0');
会出现编译器错误消息(错误 C2666)。
for debug purposes I often output pointer values (mostly this
) to qDebug:
qDebug("pointer of current object = 0x%08x",this);
, using "%08x" as format string and simply passing this
as a parameter.
How can I convert the pointer value to a QString?
This is what I got so far:
char p = (char)this;
return QString("0x%1").arg(p, 8, '0');
But the compiler doesn't seem to figure out what to do with that value. Is casting to char
correct in this case? Or what would be a safer way to do this?
Using Visual C++ with Qt 4.7.4.
EDIT
Using qulonglong
as suggested
qulonglong p = (qulonglong)this;
return QString("0x%1").arg(p, 8, '0');
yields in a compiler error message (error C2666).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 QString::arg():
它将使用指针的正确类型和大小(
quintptr
和QT_POINTER_SIZE
),并且始终带有前缀“0x”
。注释:
要为值添加零前缀,第四个参数需要为
QChar('0')
。要输出正确的位数,
QT_POINTER_SIZE
需要加倍(因为每个字节需要 2 个十六进制数字)。Using QString::arg():
It will use the correct type and size for pointers (
quintptr
andQT_POINTER_SIZE
) and will always prefix"0x"
.Notes:
To prefix the value with zeros, the fourth parameter needs to be
QChar('0')
.To output the correct number of digits,
QT_POINTER_SIZE
needs to be doubled (because each byte needs 2 hex digits).为什么不简单地使用 QString & QString::sprintf ( const char * cformat, ... )
Why not simply use
QString & QString::sprintf ( const char * cformat, ... )
QTextStream 似乎提供了您寻求的功能,并且只需在 <代码>无效*。
与其他方法不同,它不引用特定数字“8”或转换为“qlonglong”等概念。看起来不那么令人担忧,并且很像 std::string 的规定方法 (尽管没有涉及
std::string
转换)QTextStream appears to offer the functionality you seek, and operates simply on a
void*
.Unlike the other approaches, it does not reference notions like the particular number "8" or casting to "qlonglong". Seems less worrisome, and is much like the prescribed method for std::string (though without getting
std::string
conversions involved)您可以使用
sprintf
执行中间步骤:或通过
ostringstream
:You could do an intermediate step with
sprintf
:Or through
ostringstream
:对我来说,大多数情况下,查看指针是否为 nullptr 或者它是否与其他指针具有相同的值就足够了。对于这些情况,将指针转换为数字然后使用 QString::number() 就足够了
For me mostly it is enough to see if the pointer is the
nullptr
or if it has the same value as an other pointer. For those cases it is enough to convert the pointer to a number and then useQString::number()