4

C++命名空间_酋长的技术博客_51CTO博客

 2 years ago
source link: https://blog.51cto.com/u_15433911/5473028
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C++命名空间

原创

落花有意,流水无情 2022-07-14 18:21:03 ©著作权

文章标签 命名空间 c++ 作用域 文章分类 C/C++ 编程语言 阅读数167

1、命名空间是ANSI C++引入的可以由用户命名的作用域,用来处理程序中常见的同名冲突。C++引入了类作用域的概念,类是出现在文件内,在不同的作用域中可以定义相同名字的变量,互不干扰便于系统区别他们。

例如:在有些情况,不同的厂商设计出不同的库文件,但厂商之间可能使用同名的函数,但不同厂商设计的函数有不同的功能,所以用户在使用这些函数的时候就会造成歧义。因此C++引入命名空间来解决类似的同名冲突。

下面通过一个简单的实例来认识C++命名空间:

​#include<iostream>

//自定义命名空间W,在此命名空间下sum函数实现两个数相加

namespace W {

int sum(int x, int y);

int W::sum(int x, int y) {

return x + y;

//自定义命名空间X,在此命名空间下sum函数实现两个数相减

namespace X {

int sum(int x, int y);

int X::sum(int x, int y) {

return x - y;

void test01() {

using namespace std;

int a, b = 0;

cout << "请输入两个数:";

cin >> a >> b;

cout << "使用W命名空间下的sum函数(两个数相加)的结果为:";

cout << W::sum(a, b) << endl;

cout << "使用X命名空间下的sum函数(两个数相减)的结果为:";

cout << X::sum(a, b) << endl;

int main() {

test01();

return 0;

  • 收藏
  • 评论
  • 分享
  • 举报

上一篇:初识指针


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK