物联网-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年... 北京旅行社哪家靠谱?2026年北京十佳旅行社榜单揭秘,全是信得过的专业实力商家 在规划一次完美的北京...
2026上半年伊犁问疆行定制游... 1. 开篇导语 📅 数据统计截止时间:2026年3月5日 📍 服务覆盖范围: 本次评测聚焦于为全国乃...
解读一下曲靖亲子游好去处 # 曲靖亲子游:山水之间的温馨时光 曲靖的清晨总是带着露水的清新。这座素有“滇黔锁钥”之称的古城,不...
南湖公园最新提示 随着气温回升 我市南湖公园 近日将迎来春季游园高峰 为保护春季返青绿地、 维护游园秩序、保障游客安全...