將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:
爲啥我調用命名空間函數老是說不明確各類努力、規則都是爲了管理名字,減小名字的污染。編譯連接報「重複定義」的錯,大概就是本身做用域弄亂了。作用域