物联网-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();}

相关内容

热门资讯

山水皆有情!丽江两山一江的千年... 去过丽江、走过虎跳峡的人,大概率都听过哈巴雪山和金沙江的传说。很多人站在峡谷之下,望着奔腾不息的金沙...
活力中国调研行丨“殷”你而来 ... 9月12日,游客在殷墟博物馆“甲骨文展厅”内参观。位于河南省安阳市的殷墟博物馆新馆是首个全景式展现商...
浦江之夜赴美好相逢,第37届上... 9月12日晚,黄浦江畔灯火璀璨,第37届上海旅游节大巡游在外滩中山东一路上演。不少观众早早便来到外滩...
美丽中国丨秋韵紫鹊界 梯田入画... 这是9月11日拍摄的紫鹊界梯田(无人机照片)。 金秋九月,湖南省娄底市新化县紫鹊界梯田稻谷渐次成熟。...
中国之巅奏响《共同的节日》,千... 千吨阻尼器,“迎世赛、游上海旅游节”。9月13日,由上海市文化和旅游局指导推出上海旅游·会客│巅峰之...