C++的namespace

C++的namespace

  • 名称空间可用于区别不同人写的相同函数,在同一个源文件中共存,如下:
// 名称空间的定义和使用.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using std::cout;
using std::endl;
namespace welcome{
	int count=3;
	float getCount(){
		return 3.33f;
	}
}
using namespace welcome;
namespace hello{
	int count=4;
		float getCount(){
			return 4.44f;
		}
}
float getCount(){
	return 1.11f;
}
int main()
{
	int count=1;
	cout<<"直接调用getCount的函数和使用count"<<endl;
	//cout<<"getCount:"<<getCount()<<endl;
	cout<<"count:"<<count<<endl;
	cout<<"-----------------------------------------------------"<<endl;
	cout<<"使用标识符调用getCount函数和使用count"<<endl;
	cout<<"::getCount:"<<::getCount()<<endl;
	cout<<"count:"<<::count<<endl;
	cout<<"welcome::getCount:"<<welcome::getCount()<<endl;
	cout<<"welcome::count:"<<welcome::count<<endl;
	cout<<"::getCount:"<<hello::getCount()<<endl;
	cout<<"hello::count"<<hello::count<<endl;
	return 0;
}

  • 运行后,其输出效果,如下:
直接调用getCount的函数和使用count
count:1
-----------------------------------------------------
使用标识符调用getCount函数和使用count
::getCount:1.11
count:3
welcome::getCount:3.33
welcome::count:3
::getCount:4.44
hello::count4
发布了146 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42896653/article/details/94431862