将namespace
声明(.h
文件)和定义(.cpp
文件)的分离,而后在主流程(.cpp
文件)里调用,正确的结构以下:
namespace.cpp:ios
#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:spa
#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; }
输出:.net
2 4 first namespace function
在.h
文件中仅声明code
对变量的声明【
参考这里】:
extern {类型} {变量名};
😊难点1:
变量如何仅声明blog
.cpp
文件里,最好在局部做用域里使用using
。像上面这样的案例,在main
函数外面using namesapce first;
或者using first::f_func;
,会致使和主流程.cpp
文件里定义的全局函数f_func
冲突。难点2:
为啥我调用命名空间函数老是说不明确各类努力、规则都是为了管理名字,减小名字的污染。编译连接报“重复定义”的错,大概就是本身做用域弄乱了。作用域