重名问题的解决
//出错的程序 #include <iostream> #include <math.h> using namespace std; class point { public: double x; double y; }; double distance(point p1,point p2) { double d=sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); return d; } int main() { point p1= {3,5},p2= {6,9}; cout<<distance(p1,p2); }
//改法1:std中的名称加限制 #include <iostream> #include <math.h> class point { public: double x; double y; }; double distance(point p1,point p2) { double d=sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); return d; } int main() { point p1= {3,5},p2= {6,9}; std::cout<<distance(p1,p2); //出除了using namespace std,而在std中的cout前加上std:: }
//改法2:本地名称加限定 #include <iostream> #include <math.h> using namespace std; class point { public: double x; double y; }; double distance(point p1,point p2) { double d=sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); return d; } int main() { point p1= {3,5},p2= {6,9}; cout<<::distance(p1,p2); //保留using namespace std,而在distance前加上::,表示distance是“本地的” return 0; }
//改法3:本地改名避冲突 #include <iostream> #include <math.h> using namespace std; class point { public: double x; double y; }; double dist(point p1,point p2) //本地函数改名 { double d=sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); return d; } int main() { point p1= {3,5},p2= {6,9}; cout<<dist(p1,p2); return 0; }
//改法4:明确定义本地的命名空间 #include <iostream> #include <math.h> using std::cout; namespace mypoint { class point { public: double x; double y; }; double distance(point p1,point p2) { double d=sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); return d; } }; int main() { mypoint::point p1= {3,5},p2= {6,9}; cout<<distance(p1,p2); //不使用std命名空间 return 0; }