operator << overload

不打扰是莪最后的温柔 提交于 2019-12-08 02:54:18

问题


//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 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. 

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


回答1:


You have using std::ofstream instead of using std::ostream, so it doesn't know what ostream 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):

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



回答2:


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 access std::ofstream as ofstream.

You also seem to need a #include <iostream>; that's why the compiler doesn't know what ostream is. Put that in, change the friend declaration to friend std::ostream& operator<< (std::ostream&, const Dog&);, and get rid of all the using stuff, since it's bad form to put using in a header, and you should be okay.



来源:https://stackoverflow.com/questions/2695753/operator-overload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!