// template class for 3D vectors, plus test main #include template class Vector { public: // ---- constructors ---- Vector(T init_x = 0, T init_y = 0, T 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 ---- T get_x(void) const // postcondition: return value is x coordinate { return x; } T get_y(void) const // postcondition: return value is y coordinate { return y; } T 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: T x, y, z; }; // ---- nonmember functions ---- template Vector add(const Vector & v1, const Vector & v2) // postcondition: return value is sum of v1 and v2 { return Vector(v1.get_x() + v2.get_x(), v1.get_y() + v2.get_y(), v1.get_z() + v2.get_z()); } template Vector subtract(const Vector & v1, const Vector & v2) // postcondition: return value is difference of v1 and v2 { return Vector(v1.get_x() - v2.get_x(), v1.get_y() - v2.get_y(), v1.get_z() - v2.get_z()); } // ---- 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"); Vector z1 = Vector(1.1, 2.2, 3.3); Vector z2 = Vector(2.2, 4.4, 6.6); Vector ztemp; z1.show("z1"); z2.show("z2"); ztemp = add(z1, z2); ztemp.show("z1 + z2"); ztemp = subtract(z1, z2); ztemp.show("z1 - z2"); return 0; }