[源碼下載]
作者:webabcd
介紹
不可或缺 Windows Native 之 C++
示例
CppNamespace.h
#pragma once
#include <string>
using namespace std;
// 定義一個命名空間,並在其中定義一個類以及聲明一個函數
namespace NativeDll
{
class CppNamespace
{
public:
string Demo();
public:
string Demo2();
};
string demo3();
string demo4();
}
CppNamespace.cpp
/*
* 命名空間
*/
#include "pch.h"
#include "CppNamespace.h"
using namespace NativeDll;
// 不指定命名空間則是全局的
void namespace_demo1();
void namespace_demo2();
void namespace_demo3();
// 實現 NativeDll 命名空間中的函數
string CppNamespace::Demo() // 寫全了就是 string NativeDll::CppNamespace::Demo()
{
// 命名空間的定義及使用
namespace_demo1();
// 命名空間的嵌套及使用
namespace_demo2();
// 沒有名字的命名空間的定義及使用
namespace_demo3();
return Demo2() + demo3() + demo4();
}
// 實現 NativeDll 命名空間中的函數
string NativeDll::demo3() // 必須要指定命名空間,否則就是全局的
{
return "demo3";
}
// 實現 NativeDll 命名空間中的函數
namespace NativeDll
{
string CppNamespace::Demo2()
{
return "Demo2";
}
string demo4()
{
return "demo4";
}
}
// 定義 2 個命名空間
namespace ns1
{
string getString()
{
return "ns1";
}
}
namespace ns2
{
string getString()
{
return "ns2";
}
}
namespace ns2 // 命名空間是可以多次定義的
{
string getString2()
{
return "ns2 getString2";
}
}
// 命名空間的使用
void namespace_demo1()
{
string result = "";
// 調用指定命名空間下的函數
result = ns1::getString(); // ns1
result = ns2::getString(); // ns2
// 引入指定的命名空間
using namespace ns2; // 之後 ns2 有效
result = getString(); // ns2
using namespace ns1; // 之後 ns1 和 ns2 同時有效
// result = getString(); // 編譯錯誤,因為不明確
// 引入指定命名空間的指定函數
using ns1::getString; // 之後如果使用 getString() 函數,則其是來自 ns1 下的
result = getString(); // ns1
// using ns2::getString; // 編譯錯誤,和 using ns1::getString; 沖突了
}
// 定義 1 個嵌套的命名空間
namespace nsA
{
string getString()
{
return "nsA";
}
namespace nsB
{
string getString()
{
return "nsB";
}
}
}
void namespace_demo2()
{
string result = "";
// 嵌套命名空間的使用
result = nsA::nsB::getString(); // nsB
// 可以為嵌套命名空間設置別名(非嵌套的命名空間也可以設置別名)
namespace ns = nsA::nsB;
result = ns::getString(); // nsB
}
// 在名為 nsX 的命名空間下定義一個沒有名字的命名空間
namespace nsX
{
// 匿名命名空間
namespace
{
string getStringAnonymous()
{
return "getStringAnonymous";
}
}
// 內部可以直接調用沒有名字的命名空間下的函數
string getString()
{
return "getString() " + getStringAnonymous();
}
}
void namespace_demo3()
{
string result = "";
// 外部也可以直接調用指定命名空間下的匿名命名空間中的函數
result = nsX::getStringAnonymous(); // getStringAnonymous
result = nsX::getString(); // getString() getStringAnonymous
}
OK
[源碼下載]