重载ostream<<操作者

时间:2015-11-01 21:42:16

标签: c++

我有一个不可变的标题:

typedef class Foo
{
    public:
         friend ostream& operator<<(ostream&, Foo&);
}*pFoo, **ppFoo;

我试图像这样实现运营商:

#include <iostream>
using namespace std;
#include "Foo.h"

ostream& operator<<(ostream& a, Foo& b){
     a << endl;
     return a;
}

这会引发这些错误:

Error   3   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int   (foo.h)

Error   5   error C2805: binary 'operator <<' has too few parameters    (foo.h)
Error   2   error C2433: 'ostream' : 'friend' not permitted on data declarations (foo.h)
Error   4   error C2061: syntax error : identifier 'ostream' (foo.h)

请记住,标题无法触及,我该怎么办?

1 个答案:

答案 0 :(得分:2)

如果那是整个标题,那么它就会被破坏。缺少#include <ostream>std::

由于您无法更改,因此您必须:

  • 痛苦地抱怨
  • 在加入之前加入<ostream>using namespace std(您已经差不多这样做了)

从C ++ 11开始,包括<iostream>实际上就足够了as it happens, with my compiler I cannot reproduce your problem with C++03 either。但是在C ++ 03中,可能你需要单独#include <ostream>(前者不能保证包括后者),而且我可以从中猜到提供的信息有限。