简体   繁体   中英

can "using namespace std;" and "std::cout" be used together?

No an error occurs when using using namespace std; and std::cout together. Can these two be used together?

#include <iostream>
using namespace std;

int main() {
    
    std::cout << "Hello world!";

    return 0;
}

There is no problem. In this statement

std::cout << "Hello world!";

there is used the qualified name lookup of the name cout in the namespace std .

You could also write

cout << "Hello world!";

and in this case there would be used the unqualified name lookup and the name cout would be found due to the directive

using namespace std;

You could also include the using declaration like

using std::cout;

Pay attention to that you should avoid to use the using directive. It can be a reason of ambiguity. It is much better to use qualified names.

The purpose of namespace is to protect against collision. When you type in using namespace std; it turns off that protection. This lets you use cout , string , vector ... without std:: resolution, but they may collide with other namespaces.

In some tutorials you may see using namespace std; They put that in there to make the examples shorter without having to type in std:: every where. But that usage is limited to short examples. For actual code it is recommended not to add using namespace std;

You can always use std::cout , std::string , std::vector etc. without worrying about collision.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM