C++学习之namespace的用法

fish.h

#ifndef __test_header__fish__
#define __test_header__fish__

#include <stdio.h>
namespace ns_fish {
    void fish_show();
}
#endif /* defined(__test_header__fish__) */
fish.cpp
#include <iostream>
#include "fish.h"
using namespace std;
//using namespace ns_fish;

void fish_show() {
    cout<<"fish show"<<endl;
}

cat.h

#ifndef __test_header__cat__
#define __test_header__cat__

#include <stdio.h>
namespace ns_cat{
    void cat_show();
}
#endif /* defined(__test_header__cat__) */
cat.cpp
#include <iostream>
#include "cat.h"
//using namespace ns_cat;
using namespace std;

void cat_show(){
    cout<<"cat show"<<endl;
}

main.cpp

#include <iostream>
#include "fish.h"
#include "cat.h"
using namespace std;
using namespace ns_cat;
using namespace ns_fish;
int main(int argc, const char * argv[]) {
    // insert code here...
    fish_show();
    cat_show();
    return 0;
}

如果按照以上方式组织代码,编译能够通过,但是会出现链接错误,原因在于对cat_show函数和fish_show函数的定义前没有加上各自的命名空间比如ns_fish::fish_show而是直接定义了fish_show函数,fish_show和ns_fish命名空间下的fish_show函数其实是两个同名不同域的函数,所以在对main函数中fish_show和cat_show进行链接操作时会报错说没有对ns_fish::fish_show函数进行定义,所以在定义函数时需要加上各自的命名空间,那能不能用一个using namespace来代替呢,省的每次写都很麻烦,答案是不能的,因为如果你想定义两个不同命名空间的同名函数的话,你在文件前面用using namespace将这两个命名空间都加进来,可是在定义函数的时候不加命名空间,函数又同名,参数甚至也相同,这个时候系统怎么会知道你想定义哪个命名空间下的函数呢,所以不同于在main函数中调用时可以使用using namespace来减少代码量,在定义时不能够使用using namespace来定义函数(即函数调用可以用using namespace,而函数定义不行)。


如果在cat.cpp文件中定义另一个cat_show函数,该函数不在命名空间ns_cat下的话,mian中直接调用cat_show就会产生编译错误,提示歧义,所以这时候就必须在调用时加上命名空间以示区分,而不能单独用using namespace来区分。


最佳实践:头文件中不应该包含using声明,因为这样就会导致包含了该头文件的其他文件被迫使用了某个未知的命名空间,可能会导致意想不到的名字冲突问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值