issue with “using namespace std;”

2019-01-29 09:08发布

I have a source code file in C++. Here it is:

#include <iostream>
using namespace std;

class myPoint
{
public:
    double x;
    double y;
    myPoint() {x=y=0;}
};

double distance(myPoint A, myPoint B)
{
    return (A.x - B.x);
}

int main()
{
    myPoint A, B;
    A.x=5; A.y=5;
    B.x=3; B.y=2;
    cout << distance(A, B) << endl;
    return 0;
}

And my compiler (Microsoft Visual Studio C++ 2012) gives me the following error:

...
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\xutility(364): error C2039: 'iterator_category' : is not a member of 'myPoint'
1> d:...\source.cpp(5) : see declaration of 'myPoint'
...

When I removed using namespace std; and changed cout << distance(A, B) << endl; to std::cout << distance(A, B) << std::endl; my program worked.

Why does the first version give me an error? What is the mistake?

3条回答
霸刀☆藐视天下
2楼-- · 2019-01-29 09:22

Why I cannot use 1st version of the source code? Where

Because you inadvertently pulled in a name from the std namespace (std::distance) that is the same as a name of something else you defined (distance). This gives you a conflict.

Where is the mistake?

The fundamental mistake is to say using namespace std;, especially if you don't know every single name in the standard library, past and future.

It would also make sense to define your own names inside your own namespace.

namespace mystuff {
  class Point { ... };
  double distance(const Point& A, const Point& B);
}
查看更多
Bombasti
3楼-- · 2019-01-29 09:28

There is a std::distance in standard library and it become visible because of using namespace std; and it seems that for some reason it was picked instead of your version.

Do not use using namespace std;. And if you insist, do not use names which sounds like common english words, because they are likely to clash with library names.

查看更多
叛逆
4楼-- · 2019-01-29 09:34

You have a conflict with std::distance

查看更多
登录 后发表回答