【问题标题】:qDebug() not showing const std::string&qDebug() 不显示 const std::string&
【发布时间】:2015-02-06 03:47:11
【问题描述】:

我正在尝试将一些矢量数据的名称与struct 一起使用。我正在尝试查看qDebug()中的哪个名字

为了更清楚:

const std::string& testName = "asdfqwer";
qDebug() << testName;

它在构建中给出错误消息:

Error: no match for 'operator<<' in 'qDebug()() << testName'

我没有更改const std::string&amp; 类型的选项。你能在不改变类型的情况下帮我解决这个问题吗?

【问题讨论】:

    标签: c++ string qt qdebug


    【解决方案1】:

    qDebug()std::string 一无所知,但它适用于const char*。合适的运营商你可以找到here。您可以使用data()c_str() 来实现这一点,这比Jiří Pospíšil 说的要好。

    例如:

    const std::string& testName = "asdfqwer";
    qDebug() << testName.data() << testName.c_str();
    

    您还可以使用QString::fromStdStringstd::string 转换为QString

    【讨论】:

    • 同样,您可以使用 QString::fromStdString 转换为 QString
    • 太棒了.. 我不知道 qDebug() 的行为
    • 最好使用c_str() 而不是data(),因为后者不需要以空值结尾(C++11 之前)。
    • @johngull 是的,你是对的,但我认为 OP 在这里只使用 C++ 类型,但我添加了这个来回答,它是正确的,OP 可以选择他想要的。
    • @JiříPospíšil 我将 c_str() 添加到我的答案中。谢谢。
    【解决方案2】:

    如果您需要经常在代码中将 std::string 写入 qDebug(),您可以全局实现此功能(例如在您 main.cpp 中):

    #include <QDebug>
    #include <string>
    
    QDebug& operator<<(QDebug& out, const std::string& str)
    {
        out << QString::fromStdString(str);
        return out;
    }
    
    int main()
    {
        std::string jau = "jau";
        qDebug() << jau;
        return 0;
    }
    

    【讨论】:

    • 这会复制QDebug 对象。您不应该返回参考吗?
    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    相关资源
    最近更新 更多