开发者

using namespace in function implementation [closed]

开发者 https://www.devze.com 2023-02-06 18:59 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so t开发者_如何学Gohat it can be reopened, visit the help center. Closed 9 years ago.

In C++, could I use using namespace std; declaration in the function implementation files?


Maybe you would like to know too that you can put using namespace std; within a function body as well, like below. This will restrict the scope of the using namespace statement.

void f() {
  using namespace std;
  cout << "Foo" << endl;
  //..
};

void g() {
  cout << "Bar" << endl; //ERROR: cout and endl are not declared in this scope.
};

This can be useful if you want to use a lot of elements of a namespace in the body of a function that is written in a header file (which you shouldn't per se, but sometimes it is OK or even almost necessary (e.g. templates)).


By "function implementation files" do you mean the .h files or the .cpp files? (I would normally call .cpp files "implementation" files, while .h files are "interface" files.)

If you mean, .cpp files, then of course. That is where you normally see using namespace std. It means that all the code in this .cpp file has access to std without qualification.

If you mean .h files, then you can, but you shouldn't. If you include it in a .h file, it will automatically apply to any .cpp file which includes the .h file, which could be a lot of files. You generally don't want to be telling other modules which namespaces to import. It is best to put it in every .cpp file rather than in a common .h file.

Edit: User @lachy suggested an edit which I won't include verbatim, but they suggested I point out that using namespace std is usually considered bad practice, due to namespace pollution. They gave a link to a question on this topic: Why is "using namespace std;" considered bad practice?


I'm assuming you mean something like this:

// Foo.h

void SayHello();

...

// Foo.cpp

#include "Foo.h"

using namespace std;

void SayHello()
{
    cout << "Hello, world!" << endl;
}

If that is the case, then yes. However, it's considered bad practice to use using namespace std; in larger projects.


if by "function implementation files" you mean the .C/.cpp etc. files, you can, however try to avoid. Instead inject what you need in only, for example if you need <iostream> for std::cout, std::endl etc. just inject these two in, using std::cout; and using std::endl;, now you can simply write cout and endl.

0

精彩评论

暂无评论...
验证码 换一张
取 消