Overloading operator<< for primitive types.

2019-07-04 07:18发布

问题:

Hey. Is it possible to overload operator<< for primitive types? Fx lets say that I want to write a std::endl each time want to write a int. Can I overload operator<< for int, so that it automatic puts a std::endl to the output? I have tried with this,

std::ostream& operator<<(std::ostream& strm, int & i)
{
   strm << i << std::endl;
   return strm;
}

but it doesn't work. I cant recall the compiler error message, but I think that I'm getting operator overloading all wrong any ways. I try to call the above overloaded operator<< in this way,

int main()
{
   int i = 2;
   std::out<<"Here is an int " << i;

   return 0;
}

But it doesn't work at all. Maybe I can't overload POD types?

回答1:

As zabzonk said, the standard library provides an (ostream&, int) overload so you can't define another.

To simulate what you were doing (though it is completely pointless in its present form :) :

class EndlinedInteger {
public:
    EndlinedInteger(int i) : i(i) { }
    friend ostream& operator<<(ostream&, EndlinedInteger const&);
private:
    int i;
};

ostream& operator<<(ostream& out, EndlinedInteger const& ei) {
    out << ei.i << endl;
    return out;
}

int main()
{
   EndlinedInteger i = 2;
   std::cout<<"Here is an int " << i;
}


回答2:

Remember that here you use << operator not only on int but also on ostream. You could derive from ostream and implement it in your own derived class, but I would suggest to make a simple macro like

#define EL(i) (i)<<std::endl

Alternatively you could make boxed int class and override the << for standard ostream and boxed int (like in answer by Iraimbilanja) class. Sounds like huge overkill but could work.



回答3:

Your problem is that there is already an overload for operator << (ostream &, int), the one supplied by the C++ standard library. If you remove the overload definition and use:

#include <iostream>
int main()
{
   int i = 2;
   std::out<<"Here is an int " << i;

   return 0;
}

things work as expected.

And BTW, compiler error messages are kind of important, so it's a good idea to remember them and quote them in posts when asking questions.

edit - std::out above should of couse be std::cout