运算符 <<超载
//using namespace std;
using std::ifstream;
using std::ofstream;
using std::cout;
class Dog
{
friend ostream& operator<< (ostream&, const Dog&);
public:
char* name;
char* breed;
char* gender;
Dog();
~Dog();
};
我试图超载<<操作员。我也在尝试练习良好的编码。但除非我取消注释 using 命名空间 std,否则我的代码将无法编译。我不断收到此错误,但我不知道。我使用 g++ 编译器。
Dog.h:20: error: ISO C++ forbids declaration of ‘ostream’ with no type
Dog.h:20: error: ‘ostream’ is neither function nor member function; cannot be declared friend. if i add line using std::cout; then i get this error.
Dog.h:21: error: ISO C++ forbids declaration of ‘ostream’ with no type.
有人可以告诉我超载 << 的正确方法吗?不带 out using 命名空间 std 的运算符;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用的是
using std::ofstream
而不是using std::ostream
,因此它不知道ostream
是什么。您还需要包含
。但实际上,没有理由使用
使用任何东西
;您应该只使用名称空间来限定名称(特别是如果这是头文件,以避免污染其他文件的全局名称空间):You have
using std::ofstream
instead ofusing std::ostream
, so it doesn't know whatostream
is.You also need to include
<ostream>
.Really, though, there's no reason to use
using anything
; you should just qualify the names with the namespace (especially if this is a header file, to avoid polluting the global namespace of other files):using
关键字只是意味着让您可以访问某些内容,而无需为其添加名称空间前缀。换句话说,using std::ofstream;
只是说让您以ofstream
的方式访问std::ofstream
。您似乎还需要一个
#include
;这就是为什么编译器不知道ostream
是什么。将其放入,将友元声明更改为friend std::ostream&运算符<< (std::ostream&, const Dog&);
,并删除所有using
内容,因为将using
放在标头中是一种不好的形式,你应该没问题。The
using
keyword just means to let you access something without prefixing it with its namespace. In orther words,using std::ofstream;
just says to let you accessstd::ofstream
asofstream
.You also seem to need a
#include <iostream>
; that's why the compiler doesn't know whatostream
is. Put that in, change the friend declaration tofriend std::ostream& operator<< (std::ostream&, const Dog&);
, and get rid of all theusing
stuff, since it's bad form to putusing
in a header, and you should be okay.