C++ 将std::string转换为QString

C++ 将std::string转换为QString,c++,qt,C++,Qt,我有一个如下所示的函数,我正在尝试打印QT中的值 void myfunction( std::string& Service, std::string& Type, std::string& Hostname, std::string& Address, UNUM16 Port, std::map< std::string, std::string >& TxtL

我有一个如下所示的函数,我正在尝试打印QT中的值

void myfunction(
    std::string&    Service,
    std::string&    Type,
    std::string&    Hostname,
    std::string&    Address,
    UNUM16      Port,
    std::map< std::string, std::string >& TxtList )
{
    qDebug() << "Hostname capacity is : " << Hostname.capacity();
    qDebug() << "Hostname is : " << QString::fromStdString(Hostname);
    qDebug() << "Port is : " << ntohs(Port);

    std::map< std::string, std::string >::iterator iter;
    iter = TxtList.find("FwVersion");

}
void myfunction(
字符串和服务,
std::字符串和类型,
std::字符串和主机名,
std::字符串和地址,
UNUM16端口,
std::map&TxtList)
{
qDebug()来自

QString QString::fromStdString(const std::string&str)[静态]

返回str字符串的副本。给定字符串将转换为 使用fromAscii()函数的Unicode。此构造函数仅适用于 如果Qt配置为启用STL兼容性,则可用


您不应该使用
QString::fromUtf8()
,因为std::string不是UTF8编码的(除非您以某种方式将编码的字符串放在那里)

通常不应将
std::string
作为引用传递。它有自己的副本构造函数。@Qix,通过常量引用传递它是常见的。通过非常量引用传递它应该遵守与通过非常量引用传递任何其他内容相同的规则:如果需要更改它并传播这些更改。@devana,请发布一个带有字符串的t给出您描述的行为。@chris他们不是通过const引用传递。@chris上面的函数是我正在使用的库中的回调函数。我必须使用std::string引用本身作为输入参数,并且我不能更改函数的签名。我尝试在没有引用的情况下创建一个变量作为值t键入并使用QString::fromstdstring在这种情况下有效。但当声明为referenece的字符串时就不行了。
std::string
允许UTF8编码,当然。ASCII本质上是UTF8编码的,UTF8允许正确的以null结尾的字符串。使用
std::string
调用
QString::fromUtf8()。