| namespaces/point-namespace-2.cc - Same with illustration of ambiguities relative to the global namespace. | Lecture 4 - slide 3 : 41 Program 3 |
// Illustrating ambiguities and the global namespace
#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));
}
// A funny move function. Move in the global namespace
void move(PointNamespace::Point &p, double dx, double dy){
p.x += 2 * dx; p.y += 2 * dy;
}
int main(){
PointNamespace::Point
p = {0,0},
q = {3,4},
r = {5,6};
PointNamespace::move(p,2,3); // call move in PointNamespace.
PointNamespace::move(q,4,5); // Now necessary to quality with the namespace.
::move(p,5,6); // call move in the global namespace.
double d = distance_to(q,r);
cout << d << endl; // 3.60555
cout << "Point p: " << getx(p) << ", " << gety(p) << endl; // 12, 15
cout << "Point q: " << getx(q) << ", " << gety(q) << endl; // 7, 9
}