美文网首页想法简友广场
每天一个知识点(六)

每天一个知识点(六)

作者: 少年小马 | 来源:发表于2020-03-31 10:23 被阅读0次

对namespace的理解。

C++中为什么使用命名空间namespace,举个例子,一个数学老师带着两个班级的课,每个班级里面都有一个数学课代表。现老师让你去把数学课代表找来,此时你就会有疑问是找哪个班级的。这里就需要命名空间来区分,比如一班的数学课代表。

当然在C++程序中也会出现同样的问题,比如你正在调用一个名为function()的函数,此时有两个可用的库中都包含这个函数,所以编译器就不知道你到底需要哪一个。命名空间就是用来区分不同类或者库的同名函数。命名空间的本质就是定义了一个范围,我们找一个东西,需要现确定它所在的范围。

定义名为class_one和class_two的命名空间,并调用。

代码:

#include <iostream>

using namespace std;

//命名空间一班

namespace class_one {

//函数,类名等等

void student() {

cout << ’’ Xiao Ming is the representative of mathematics class’’ << endl;

}

}

//命名空间二班

namespace class_two {

void student() {

cout << ’’ Xiao hong is the representative of mathematics class’’ << endl;

}

}

int main () {

class_one::student();

class_two::student();

return 0;

}

在student函数内用了两个命名空间(namespace),输出的结果是:

’’ Xiao Ming is the representative of mathematics class’’

’’ Xiao hong is the representative of mathematics class’’

使用using关键词也可以指定特定的命名空间。

#include <iostream>

using namespace std;

//命名空间一班

namespace class_one {

//函数,类名等等

void student() {

cout << ’’ Xiao Ming is the representative of mathematics class’’ << endl;

}

}

//命名空间二班

namespace class_two {

void student() {

cout << ’’ Xiao hong is the representative of mathematics class’’ << endl;

}

}

//这里使用using的方法

using namespace class_one;

int main () {

student(); //这里直接调用student()即可,不必指明所属命名空间

return 0;

}

输出结果:

’’ Xiao Ming is the representative of mathematics class’’

相关文章

  • 每天一个知识点(六)

    对namespace的理解。 C++中为什么使用命名空间namespace,举个例子,一个数学老师带着两个班级的课...

  • 完整的整合营销传播套路梳理

    每天学习一个营销知识点,每天梳理营销知识点,每天分享一个营销知识点。 今天梳理下整合营销传播的整体构建框架怎么做?...

  • 每天一个知识点

    图像识别与目标检测: 输入一张图片,输出与该图片对应的类别属于图像识别。如果输出的不单单是图像类别,还包括图像中所...

  • 每天一个知识点

    Toast.LENGTH_SHORT和 Toast.LENGTH_LONG分别对应多长时间? 多次调用toast....

  • 84.Kotlin object 和 companion obj

    object EightyFourActivity {/**** 每天一个知识点day84 TODO Kotlin...

  • 每天一个知识点(二)

    有时候,同样的代码源程序与交互式终端的执行结果不同。这是因为源程序是一次执行,系统只开辟一个内存空间,这让相同的数...

  • 每天一个知识点(四)

    介绍几个数据集 LFW(labeled faces in the wild)人脸数据库: 主要用来研究非受限情况下...

  • 每天一个知识点(五)

    今天介绍一个特殊的向量。 one hot(独热)向量: ti={0,0,0,...,1,...0} one ho...

  • 每天一个知识点(八)

    TensorFlow的数据读取机制:(读取图片为例) 如果将图片先读取到内存中后提供给GPU或CPU计算,...

  • 每天一个知识点(七)

    介绍几个常用的字符串处理。 一、列表元素删除: ①知道要钱处对象的位置。del函数 ②知道要删除的具体元素。rem...

网友评论

    本文标题:每天一个知识点(六)

    本文链接:https://www.haomeiwen.com/subject/gcaiuhtx.html