![]() ![]() ![]() | namespaces/point-namespace-1.cc - A namespace with struct Point in C++ . | Lecture 4 - slide 3 : 41 Program 2 |
// A namespace programmed in a similar way as struct Point. #include <cmath> #include <iostream> using namespace std; namespace PointNamespace { struct Point{ double x, y; }; double getx (Point); double gety (Point); void move(Point&, double, double); double distance_to(Point, Point); }; double PointNamespace::getx (Point p){ return p.x; } double PointNamespace::gety (Point p){ return p.y; } void PointNamespace::move(Point &p, double dx, double dy){ p.x += dx; p.y += dy; } double PointNamespace::distance_to(Point p, Point other){ return sqrt((p.x - other.x) * (p.x - other.x) + (p.y - other.y) * (p.y - other.y)); } int main(){ PointNamespace::Point p = {0,0}, q = {3,4}, r = {5,6}; move(p,2,3); // It is not necessary to qualify move with its namespace because move(q,4,5); // move is looked up in the namaspace of its argument (stroustrup page 177). double d = distance_to(q,r); cout << d << endl; // 3.60555 cout << "Point p: " << getx(p) << ", " << gety(p) << endl; // 2, 3 cout << "Point q: " << getx(q) << ", " << gety(q) << endl; // 7, 9 }