运算符<<超载 [英] operator << overload

查看:133
本文介绍了运算符<<超载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//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();

};

im试图使<<操作员.我也在尝试练习良好的编码.但是除非我取消对using名称空间std的注释,否则我的代码将无法编译.我不断收到此错误,我不知道.我正在使用g ++编译器.

im trying to overload the << operator. I'm also trying to practice good coding. But my code wont compile unless i uncomment the using namespace std. i keep getting this error and i dont know. im using g++ compiler.

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. 

有人可以告诉我过载<<的正确方法吗?运算符,不使用命名空间std;

Can somebody tell me the correct way to overload the << operator with out using namespace std;

推荐答案

您使用的是using std::ofstream而不是using std::ostream,因此它不知道ostream是什么.

You have using std::ofstream instead of using std::ostream, so it doesn't know what ostream is.

您还需要包含<ostream>.

但是,确实没有理由使用using anything.您应该只用名称空间来限定名称(尤其是,如果这是一个头文件,以避免污染其他文件的全局名称空间):

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):

friend std::ostream& operator<< (std::ostream&, const Dog&);

这篇关于运算符&lt;&lt;超载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆