1

```

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

```

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

4

1 回答 1

2

对于您的原始代码

Printer() << stdstring << qstring

等于

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

你可以在这里看到问题,

Printer() << stdstring

将返回 a ostream &,然后您传递QStringostream. 我认为您应该返回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();
}
于 2013-03-23T05:52:10.080 回答