命名空间到底是什么,为什么有必要 [英] What exactly is a namespace and why is it necessary

查看:308
本文介绍了命名空间到底是什么,为什么有必要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在学习C ++,在每个项目的开始,我的老师都会在一行中写上一行:

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

using namespace std;

我知道它使您不必调用包含在其标头名称中的标头中的函数,例如iostream :: stdout,而只需调用stdout即可.

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.

但是该行确切地告诉C ++要做什么.什么是名称空间,什么是std?

除了python之外,我还是编程的新手,所以切换到新范例对我来说非常令人困惑.

推荐答案

来自cppreference.com:

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.

名称空间可以避免名称冲突,例如,标准库定义了sort(),但这对于排序函数来说确实是个好名字,这要归功于命名空间,因为您可以定义自己的sort(),因为它不会在其中与标准名称空间相同.

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.

using指令告诉编译器在当前作用域中使用该名称空间,以便您可以这样做

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;
}

或:

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

当您使用其他命名空间中的很多东西时很方便.

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

来源:命名空间-cppreference.com

这篇关于命名空间到底是什么,为什么有必要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆