简体   繁体   中英

Overloading operator<< for primitive types. Is that possible?

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?

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.

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM