2

地狱 !我正在尝试创建一个可以帮助我将文本输出到标准输出的类......无论如何,除了一件事之外,一切都在工作。假设我已经创建了我的班级的对象。当我这样做时,一切正常:

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

当我这样做时它也有效:

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

但是,当我尝试将这两件事联系在一起时,就像这样:

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

我得到了那个超级大的错误,这最终告诉我 operator<< 不接受 QString 类型的参数。这很奇怪,因为当我不链接 QString 时它可以正常工作......这也有效:

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

还有这个:

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

所以我想我的 operator<< 函数有问题......要么我没有正确地制作 operator<<,要么我没有返回正确的值。或者可能有其他问题。无论如何,我无法弄清楚,所以你能帮帮我吗?下面是源代码:

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

当然,超级大错误:D

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

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

4

3 回答 3

1

你在使用命名空间吗?如果是,您是否在特定命名空间中定义了operator<<for ?QString我看不出上面的代码有什么问题(除了重载应该接受一个 const 引用而不是一个副本!)

编辑:应该添加,如果它在命名空间中,请将其移出,否则将找不到。

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

std::ostream& operator<<(std::ostream &out, const QString& var);
于 2011-02-07T15:09:37.930 回答
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;
  }

如果它也为您编译,您应该能够将其转换为失败的代码以查找错误。

于 2011-02-07T15:43:36.793 回答
1

我不得不注意到 Qt 提供了一个函数/类来做到这一点,它被称为QDebug. 由于您已经绑定到 Qt,因此使用它应该不是问题。

于 2011-02-07T15:57:55.053 回答