Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

c++ - What exactly is a namespace and why is it necessary

I am learning C++ right now, and at the beginning of every project my instructor puts a line that says:

using namespace std;

I understand that it keeps you from having to call functions in headers you include with their header name like iostream::stdout and instead just call stdout.

But what exactly does the line tell C++ to do. What is a namespace and what is std?

I am also new to programming besides python so switching to a new paradigm is very confusing for me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From cppreference.com:

Namespaces provide a method for preventing name conflicts in large projects.

Symbols declared inside a namespace block are placed in a named scope that prevents them from being mistaken for identically-named symbols in other scopes.

Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope.

A namespace works to avoid names conflicts, for example the standard library defines sort() but that is a really good name for a sorting function, thanks to namespaces you can define your own sort() because it won't be in the same namespace as the standard one.

The using directive tells the compiler to use that namespace in the current scope so you can do

int f(){
    std::cout << "out!" << std::endl;
}

or:

int f(){
    using namespace std;
    cout << "out!" << endl;
}

it's handy when you're using a lot of things from another namespace.

source: Namespaces - cppreference.com


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...