```javascript#include
#include
#include
类别打印机{
公共:
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();}私有:
std::stringstream stream;};
int main(void)
{
QString qstring("qstring");std::string stdstring("std::string");Printer() << qstring << stdstring << 1; // Works like charmPrinter() << stdstring << qstring << 1; // Doesnt work :(return 0;}
有没有人可以看一下上面的代码,告诉我我有注释的main方法的问题是什么?
发布于 2013-03-23 13:52:10
您的原始代码
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();
}https://stackoverflow.com/questions/15583239
复制相似问题