0
//vector.h
        struct Vector
    {
        public:
        double x;
        double y;
        double z;
    }

I have this library which provides me with certain classes and their methods. How do I extend these classes in my own application code?

right now I am memcopy this vector into a char array and then udp sending it, and then udp receive on the other side and then memcopy ing it into a vector instance from a char array with 3*sizeof(double).

How do I extend the struct or similar classes so that I can simply

std::string<<vector;

and then send this string to my udp send

and udp receive and then copy the received message directly into a vector?

1 Answers1

2

You need/want an overload of operator<<:

std::ostream &operator<<(std::ostream &os, Vector const &v){ 
   return os << v.x << "\t" << v.y << "\t" << v.z;
}

Note that instead of writing directly to a string, you'll use this to write to an std::ostringstream (but it's trivial to get an std::string of the contents of a stringstream.

For reading, you do pretty much the same thing with operator>>:

std::istream &operator>>(std::istream &is, Vector &v) { 
    return is >> v.x >> v.y >> v.z;
}

Note that when you write, this does not automatically insert delimiters between the Vector objects. Typically you'll want to insert something like\n between one Vector and the next.

Also note that this stores the data in text format. Depending on your situation, you may prefer binary -- it's generally more compact and faster to read and write (but also more fragile, so seemingly minor corruption can destroy an entire file).

Oh -- one other detail. In case it wasn't clear, these functions should not be members of your Vector class, but if you put Vector into namespace, you want to keep these functions in the same namespace with it.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111