LovesPie LovesPie - 1 month ago 10
C++ Question

C++ How do I print an object?

I have created a constructor

Location(double xIn,double yIn,string placeIn,int timeIn)
: x(xIn),y(yIn) ...so on {


Say I want to print Location home(x,y,place,time); that's in the
main()
.

How would I do so? I've been searching around and was told to use
operator<<
. How would I implement this?

UPDATE: After creating some get methods and I tried doing,can't exactly compile it because of the problem

ostream &operator<<(ostream & o, const Location & rhs){

o << rhs.getX() << "," << rhs.getY() << "," << rhs.getPlace() << "," << rhs.getTime();
return o; }

Answer

Here is the stencil for overloading operator<<:

class Any
{
  public:
    friend std::ostream& operator<<(std::ostream& output, const Any& a);
  private:
    int member;
};

std::ostream&
operator<<(std::ostream& output, const Any& a)
{
  output << a.member;
  return output;
}

This one possible stencil, there are other possibilities. Search the internet for "c++ stream insertion operator overload example" for other implementations.

Comments