见鬼!我正在尝试创建一个类来帮助我将文本输出到标准输出......无论如何,一切都正常,除了一件事。假设我已经创建了调用的类的对象。当我这样做时,一切正常:
out<<"test test"<<std::endl;
当我这样做时它也有效:
out<<QString("another string")<<std::endl;
但是,当我尝试将这两件事链接在一起时,如下所示:
out<<"test test"<<std::endl<<QString("another string")<<std::endl;
我得到了一个 super 大的错误,这最终告诉我operator<<不接受QString类型的参数。这很奇怪,因为当我不链接 QString 时它工作正常......这也有效:
out<<"test test"<<std::endl<<"another string"<<std::endl;
还有这个:
out<<QString("another string")<<std::endl<<"test test"<<std::endl;
所以我想我的operator<<函数有问题...要么我没有正确地创建operator<<,要么我没有返回正确的值。或者也许还有其他问题。无论如何,我无法弄清楚,所以你能帮我吗?下面是源代码:
输出.h:http://xx77abs.pastebin.com/b9tVV0AV 输出.cpp:http://xx77abs.pastebin.com/5QwtZRXc
当然,还有 super 大错误:D
http://xx77abs.pastebin.com/8mAGWn47
编辑:对于所有你想知道的,我没有使用命名空间......
最佳答案
这为我编译(使用第三个链接中的命令行):
#include <iostream>
#include <sstream>
#include <QString>
class Output: public std::ostream
{
friend std::ostream& operator<<(std::ostream &out, const QString var);
private:
class StreamBuffer: public std::stringbuf
{
private:
std::ostream &out;
QString prefix;
public:
StreamBuffer(std::ostream& str, const QString &p);
virtual int sync();
};
StreamBuffer buffer;
public:
Output(const QString &prefix);
};
Output::Output(const QString &prefix) :
std::ostream(&buffer), buffer(std::cout, prefix)
{
}
Output::StreamBuffer::StreamBuffer(std::ostream& str, const QString &p)
:out(str)
{
prefix = p + "-> ";
}
std::ostream& operator<<(std::ostream &out, const QString var)
{
out<<qPrintable(var);
return out;
}
int Output::StreamBuffer::sync()
{
out <<qPrintable(prefix)<< str();
str("");
out.flush();
return 0;
}
int main()
{
Output out (QString (">")) ;
out<<"test test"<<std::endl;
out<<QString("another string")<<std::endl;
out<<"test test"<<std::endl<<QString("another string")<<std::endl;
}
如果它也可以为您编译,您应该能够将其转换为失败的代码以查找错误。
关于c++ - 继承std::ostream 和QString 的operator<< 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4922575/