C++命名空间namespace分离声明、定义
文章目录
正确的文件结构
将namespace声明(.h文件)和定义(.cpp文件)的分离,然后在主流程(.cpp文件)里调用,正确的结构如下:
namespace.cpp:
#include <iostream>
#include "namespace.h"
namespace first {
int f_int = 4;
void f_func() {
std::cout << "first namespace function" << std::endl;
}
}namespace.h:
#pragma once
#include <iostream>
namespace first {
extern int f_int;
void f_func();
}main.cpp:
#include <iostream>
#include "namespace.h"
void f_func(void);
namespace second {
int s_int = 2;
}
int main() {
using first::f_func;
std::cout << second::s_int << std::endl;
std::cout << first::f_int << std::endl;
f_func();
return 0;
}
void f_func(void) {
std::cout << "main function" << std::endl;
}输出:
2
4
first namespace function分析
在
.h文件中仅声明对变量的声明【参考这里】:
extern {类型} {变量名};😊
难点1:变量如何仅声明
- 在主流程
.cpp文件里,最好在局部作用域里使用using。像上面这样的案例,在main函数外面using namesapce first;或者using first::f_func;,会导致和主流程.cpp文件里定义的全局函数f_func冲突。
😊难点2:为啥我调用命名空间函数总是说不明确

总结
各种努力、规则都是为了管理名字,减少名字的污染。编译链接报“重复定义”的错,大概就是自己作用域弄乱了。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论