2011-02-07 100 views
2

地狱!我正在尝试创建一个能够帮助我将文本输出到stdout的类......无论如何,除了一件事之外,一切都在起作用。假设我已经创建了我的类的对象。当我这样做,一切正常prefectly:为QString继承std :: ostream和operator <<的类

out<<"test test"<<std::endl; 

而且还当我做这个工作:

out<<QString("another string")<<std::endl; 

但是,当我试图链,这两个东西在一起,像这样:

out<<"test test"<<std::endl<<QString("another string")<<std::endl; 

我得到那个超大错误,最终告诉我,运算符< <不接受QString类型的参数。这是奇怪的,因为它的工作原理确定,当我不连锁的QString ......还有这个作品:

out<<"test test"<<std::endl<<"another string"<<std::endl; 

这:

out<<QString("another string")<<std::endl<<"test test"<<std::endl; 

所以我想我有问题,我的操作< <功能...要么我没有正确地使运营商< <,要么我没有返回正确的价值。或者也许别的东西是错的。无论如何,我无法弄清楚,所以你能帮我吗?贝娄源代码:

output.h:http://xx77abs.pastebin.com/b9tVV0AV output.cpp:http://xx77abs.pastebin.com/5QwtZRXc

当然,超级大错误:d

http://xx77abs.pastebin.com/8mAGWn47

编辑:所有你想知道,我没有使用命名空间...

+0

你从哪里测试这些打印输出? `output.cpp`? – 2011-02-07 14:57:52

回答

1

这编译为我(与你的第三个链接命令行):

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

如果它编译于你,你应该能够把它演变成发生故障的代码,以找到错误。

+0

感谢你的观点=)我试着编译你的代码,它的工作。然后我把它放在单独的文件中,它不起作用。然后我尝试了几件事,发现解决方案是将operator <<定义从.cpp移到.h文件。之后,我得到了一些有关多个定义的错误,我通过声明operator << as inline function :)来解决这个问题:)感谢您的帮助! – xx77aBs 2011-02-07 19:19:07

+1

啊,是的,现在很明显! `std :: ostream&operator <<(std :: ostream&out,const QString var)`不在头文件中声明。另一种解决方案是头文件中的`extern std :: ostream&operator <<(std :: ostream&out,const QString var);`。 – TonyK 2011-02-07 19:58:05

1

你在使用命名空间吗?如果是的话,你是否在特定的命名空间中为QString定义了operator<<?我不能看到上面的代码有任何问题(除了超载应该接受一个const引用而不是一个副本!)

编辑:应该添加,如果它是在一个命名空间,将其移出,否则它不会被发现。

EDIT2:在你的类声明之后,将operator<<的声明添加到头文件中 - 编译器在你做之前不知道这个超载的存在。

std::ostream& operator<<(std::ostream &out, const QString& var); 
+0

我没有使用名称空间...是的,我忘了输入&;)我会解决这个问题,谢谢 – xx77aBs 2011-02-07 15:17:47

1

我觉得不得不指出,Qt提供了一个功能/类来完成这个,它被称为QDebug。既然你已经绑定了Qt,使用它不应该是一个问题。

相关问题