What requires me to declare “using namespace std;”?

后端 未结 12 2211
抹茶落季
抹茶落季 2020-12-17 10:55

This question may be a duplicate, but I can\'t find a good answer. Short and simple, what requires me to declare

using namespace std;

in C+

12条回答
  •  孤街浪徒
    2020-12-17 11:14

    Firstly, the using directive is never required in C since C does not support namespaces at all.

    The using directive is never actually required in C++ since any of the items found in the namespace can be accessed directly by prefixing them with std:: instead. So, for example:

    using namespace std;
    string myString;
    

    is equivalent to:

    std::string myString;
    

    Whether or not you choose to use it is a matter of preference, but exposing the entire std namespace to save a few keystrokes is generally considered bad form. An alternative method which only exposes particular items in the namespace is as follows:

    using std::string;
    string myString;
    

    This allows you to expose only the items in the std namespace that you particularly need, without the risk of unintentionally exposing something you didn't intend to.

提交回复
热议问题