C++命名空間namespace分離聲明、定義

正確的文件結構

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:爲啥我調用命名空間函數老是說不明確
    重複定義函數f_func
    函數名不明確的報錯

總結

各類努力、規則都是爲了管理名字,減小名字的污染。編譯連接報「重複定義」的錯,大概就是本身做用域弄亂了。作用域

相關文章
相關標籤/搜索