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

相关内容

热门资讯

小雪降温,别错过这几道滋补菜,... 小雪降温,别错过这几道滋补菜,孩子一吃就两碗,御寒强免疫 小雪时节天气渐冷,下面分享几道滋补家常菜,...
原创 它... 在探讨美食的海洋中,有一种食物以其独特的魅力,成为了众多男性心中的挚爱。它不仅满足了味蕾的极致享受,...
原创 它... 标题:快餐文化下的童年记忆 在快节奏的现代生活中,快餐以其便捷、快速的特点成为了人们餐桌上的常客。...
从“蟹季限定”到“四季常热” 味觉公路 度假区(阳澄湖镇)供图 □ 本报记者 陈诚 王俊杰 入冬后,阳澄湖畔有了阵阵凉意,苏州“村...
佳木斯市再添新景 四丰山水库打... 本文转自:人民网-黑龙江频道人民网哈尔滨11月19日电 近日,佳木斯四丰山水库再添新景——沿岸休闲步...