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



``

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

```

任何人都可以看看上面的代码,告诉我主方法中的问题是什么吗?我有意见

对于您的原始代码

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();
}

相关内容

  • 没有找到相关文章

最新更新