// class for 3D vectors of ints, plus test main #include class Vector { public: // ---- constructors ---- Vector(int init_x = 0, int init_y = 0, int init_z = 0) // postcondition: x = init_x, y = init_y, z = init_z { x = init_x; y = init_y; z = init_z; } // ---- "constant" member functions ---- int get_x(void) const // postcondition: return value is x coordinate { return x; } int get_y(void) const // postcondition: return value is y coordinate { return y; } int get_z(void) const // postcondition: return value is z coordinate { return z; } void show(char identifier[]) const // postcondition: x, y, z coordinates printed to cout, // preceded by identifier and followed by endl { cout << identifier << " = ("; cout << x << ", " << y << ", " << z; cout << ")\n"; } private: int x, y, z; }; // ---- nonmember functions ---- int add(int x, int y) // postcondition: return value is x + y { return x + y; } int subtract(int x, int y) // postcondition: return value is x - y { return x - y; } Vector pairwiseOperator(const Vector & v1, const Vector & v2, int oper(const int, const int)) // postcondition: return value is produced by combining corresponding // elements of v1, v2 using oper { return Vector(oper(v1.get_x(), v2.get_x()), oper(v1.get_y(), v2.get_y()), oper(v1.get_z(), v2.get_z())); } Vector add(const Vector & v1, const Vector & v2) // postcondition: return value is sum of v1 and v2 { return pairwiseOperator(v1, v2, add); } Vector subtract(const Vector & v1, const Vector & v2) // postcondition: return value is difference of v1 and v2 { return pairwiseOperator(v1, v2, subtract); } // ---- main program to test a few things ---- int main() { Vector v1 = Vector(1, 2, 3); Vector v2 = Vector(2, 4, 6); Vector vtemp; v1.show("v1"); v2.show("v2"); vtemp = add(v1, v2); vtemp.show("v1 + v2"); vtemp = subtract(v1, v2); vtemp.show("v1 - v2"); return 0; }