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

相关内容

热门资讯

牡丹江:镜泊湖冬捕焕发渔猎文化... 本文转自:人民网-黑龙江频道 人民网牡丹江1月15日电 (记者苏靖刚)1月15日,中国·镜泊湖第十一...
1月,这菜再贵也要吃,通便排毒... 1月正值三九天,冷得人直哆嗦,再加上年底聚餐多,大鱼大肉没少吃,是不是总觉得肠胃有点“堵得慌”?这时...
原创 孩... 孩子的身高发育,除了遗传,后天营养补给至关重要。尤其是生长黄金期,充足的蛋白质、钙、维生素能为骨骼发...
出国旅行零踩坑!教育博主亲测1... 一、开篇:教育博主的旅行痛点,被这些 APP 轻松解决 身为教育博主,我平时不是在和学生家长交流...