物联网-C++——2、冒号作用域、命名空间
admin
2024-04-19 14:41:25

## ::

可以指定作用域
如下如果不加::会打印局部变量a,就近原则
冒号前为空表示全局作用域


#include 
using namespace std;int a = 100;
void test() {int a = 10;cout << ::a << endl;
}
int main()
{test();
}

## namespace
1、可以存放变量、函数、类、结构体
2、命名空间可以重名和嵌套
3、必须定义在全局范围内
定义两个命名空间
使用前需加作用域

#include 
using namespace std;namespace a{int i=100;
}
namespace  b{int i = 1000;
}int main()
{cout << a::i << endl;}

命名空间内函数声明及外部定义

#include 
using namespace std;namespace a{void test();
}
void a::test() {cout << "hello" << endl;
}int main()
{a::test();
}

无名命名空间
没有名字会在所有成员前添加static修饰
也就是所有成员都被声明为静态

#include 
using namespace std;namespace {void test() {cout << "hello" << endl;}
}int main()
{test();
}

命名空间取别名
给命名空间取一个别名

#include 
using namespace std;namespace a{void test() {cout << "hello" << endl;}
}
namespace newa = a;int main()
{newa::test();a::test();
}

using

指定使用命名空间

#include 
using namespace std;namespace a{void test() {cout << "hello" << endl;}
}
namespace b {void test() {cout << "hello xingnian" << endl;}
}namespace c{void test() {cout << "hello world" << endl;}
}int main()
{using namespace b;test();}

使用指定明明空间下的成员

#include 
using namespace std;namespace a{void test() {cout << "hello" << endl;}
}
namespace b {void test() {cout << "hello xingnian" << endl;}
}namespace c{void test() {cout << "hello world" << endl;}
}int main()
{using c::test;test();}

相关内容

热门资讯

把音乐厅搬进喀斯特溶洞是什么体...   近日,一场融合多元艺术形式的洞穴音乐会在贵州省修文县举行,五百余名观众在喀斯特溶洞之中,感受了一...
教师专享福利!北京这些景区免票... 新京报讯 据首都教育消息,教师节将至,北京多家景区为老师们准备了专属免票福利!这份优惠合集已整理好,...
黑茶,喝的是一种境界与健康 在专门用来喝黑茶的茶具“飘逸杯”里,黑茶茶汤看起来并不像“黑茶”这个名字那样黑黢黢的一团。 玻璃器皿...
上海旅游节大巡游花车阵容抢先看... 2026上海旅游节大巡游9月12日外滩启幕,21辆全新主题花车携手21支境内外表演方队联袂登场,邀你...
原创 8... 上周门诊来了位 62 岁的张阿姨,得糖尿病快五年了,平时管嘴特别严,糖果、点心、甜饮料一概不碰,连水...