【问题标题】:QString and stdstring combination doesnt work in std::stringstream - compile errorQString 和 stdstring 组合在 std::stringstream 中不起作用 - 编译错误
【发布时间】:2013-03-13 01:42:07
【问题描述】:

```

#include <iostream>
#include <sstream>
#include <QString>
class Printer {
public:
    inline std::ostream& operator<<(const std::string& str) {
    stream << str;
    return stream;
    }
    inline std::ostream& operator<<(int numb) {
    stream << numb;
    return stream;
    }
    inline std::ostream& operator<<(const QString& str) {
    stream << str.toStdString();
    return stream;
    }
    virtual ~Printer(void) {
    std::cout << stream.str();
    }

private:
    std::stringstream stream;
};

int main(void)
{
    QString qstring("qstring");
    std::string stdstring("std::string");

    Printer() << qstring << stdstring << 1;   // Works like charm
    Printer() << stdstring << qstring << 1;   // Doesnt work :(

    return 0;
}

```

任何人都可以看看上面的代码,并告诉我我有 cmets 的 main 方法中的问题是什么

【问题讨论】:

  • 查看QDebug 可能会有所帮助。
  • 我已经彻底调查过了,但不能在我的场景中使用 qdebug。我需要把它作为标准字符串放在 stringstream 中。我知道我们没有返回 ostream 的左移运算符,但有人有解决方法吗?

标签: c++ stringstream stdstring qstring ostringstream


【解决方案1】:

为您的原始代码

Printer() << stdstring << qstring

等于

(Printer().operator<<(stdstring)).operator<<(qstring)

你可以在这里看到问题,

Printer() << stdstring

将返回一个ostream &amp;,然后您将QString 传递给ostream。我认为你应该返回 Printer 而不是流。

class Printer {
public:

    virtual ~Printer(void) {
        std::cout << o.str();
    }

    std::stringstream o;
};

Printer &operator<<(Printer &p, const std::string &s)
{
    p.o << s;
    return p;
}

Printer &operator<<(Printer &p, const QString &s)
{
    p.o << s.toStdString();
    return p;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString qstring("qstring");
    std::string stdstring("std::string");
    Printer p;

    p << stdstring << qstring;

    return a.exec();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2018-12-03
    • 1970-01-01
    相关资源
    最近更新 更多