好久没看Qt,今天突然看了一下,因为看别人的代码,我自己想修改一下,发现只要用到字符串就会报错, 就连 QString str = “hello”; 也会报错,灰常的迷茫,后来查了一下才发现
在程序中定义了QT_NO_CAST_FROM_ASCII的应用程序是无法使用QString的const char*相关的API函数,因此Qt提供了QLatin1String类来更高效的利用const char*的类型,它就是一个关于const char*的一个浅封装。
只要在 .pro文件里面
DEFINES += \
QT_NO_CAST_FROM_ASCII
char*就不能转换成QString,这时候就可以用 QLatin1String来代替在所有需要QString的地方。
下面是一篇译文:
QLatin1String类对US-ASCII/Latin-1编码的字符串进行了封装。
许多QString的成员函数都用const char*代替QString作为参数实现重载。这包含拷贝构造函数,赋值操作,比较操作和其他不同的函数,比如insert(), replace(), indexOf(). 这些函数都做了优化以避免在函数调用时从const char*中构造一个QString对象。例如,假定str是QString对象,
- <span style="font-size:18px;"> if (str == "auto" || str == "extern"
- || str == "static" || str == "register") {
- ...
- }</span>
- <span style="font-size:18px;"> if (str == QString("auto") || str == QString("extern")
- || str == QString("static") || str == QString("register")) {
- ...
- }</span>
在程序中定义了QT_NO_CAST_FROM_ASCII的应用程序是无法使用QString的const char*相关的API函数,因此Qt提供了QLatin1String类来更高效的利用const char*的类型,它就是一个关于const char*的一个浅封装。如果利用QLatin1String类来写上述的程序就是
- <span style="font-size:18px;"> if (str == QLatin1String("auto")
- || str == QLatin1String("extern")
- || str == QLatin1String("static")
- || str == QLatin1String("register") {
- ...
- }</span>
得益于QString(const QLatin1String&)这个构造函数,QLatin1String可以在任何需要QString对象的地方使用,比如:
- <span style="font-size:18px;">QLabel *label = new QLabel(QLatin1String("MOD"), this);</span>