QString和stdstring组合在std :: stringstream中不起作用 - 编译错误

时间:2013-03-23 04:10:08

标签: c++ stringstream stdstring qstring ostringstream

```

#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;
}

```

任何人都可以看看上面的代码并告诉我在主要方法中我有评论的问题

1 个答案:

答案 0 :(得分:2)

原始代码

Printer() << stdstring << qstring

等于

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

你可以在这里看到问题,

Printer() << stdstring

将返回ostream &,并将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();
}