简体   繁体   English

QString到const std :: string

[英]QString to const std::string

I want to assign the value in QString to a const std::string 我想将QString中的值分配给const std :: string

QString qfile("some value");

this is the const std::string variable 这是const std :: string变量

const std::string file

The code that I m using 我正在使用的代码

file = qfile.toStdString();

above codes works fine for a normal std::string . 上面的代码对于正常的std :: string可以正常工作。 But there is some problem because of the keyword 'const'. 但是由于关键字“ const”而存在一些问题。 How do I solve it ? 我该如何解决?

Don't use the assignment operator to initialize the std::string object but rather initialize the variable directly. 不要使用赋值运算符初始化std::string对象,而是直接初始化变量。

const std::string file = qfile.toStdString();

That aside, please make sure that you're aware of what encoding QString::toStdString() uses; 除此之外,请确保您知道QString::toStdString()使用的编码方式。 unlike QString , std::string is encoding-agnostic (it's a string of bytes, not characters). QString不同, std::string与编码无关(它是字节字符串,而不是字符)。

Constants are expressions with a fixed value. 常量是具有固定值的表达式。

http://www.cplusplus.com/doc/tutorial/constants/ http://www.cplusplus.com/doc/tutorial/constants/

You can also get rid of the const by making copy of the return value of toStdString() : 您还可以通过复制toStdString()的返回值来摆脱const

QString str("text");
std::string std_str(str.toStdString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM