C#寫慣了,會覺得C這樣寫編譯會跳錯很怪,但其實前提就錯了,這是C,不是C#
在此補充範例,加強印象
class LogLevel
{
public:
static const char *Trace = "TRACE";
static const char *Debug = "DEBUG";
static const char *Info = "INFO";
static const char *Warn = "WARN";
static const char *Error = "ERROR";
};
宣告(.h)與實作(.cpp)分離即可編譯過關(也能想成是物件導向的介面與實作分離)
//宣告,一般是寫在*.h檔上
class LogLevel
{
public:
static const char *Trace;
static const char *Debug;
static const char *Info;
static const char *Warn;
static const char *Error;
};
//實作,不想公開可以寫在*.cpp檔上,想公開也可以寫在*.h檔上
const char *LogLevel::Trace = "TRACE";
const char *LogLevel::Debug = "DEBUG";
const char *LogLevel::Info = "INFO";
const char *LogLevel::Warn = "WARN";
const char *LogLevel::Error = "ERROR";
GitHub上有很多免費且公開的程式碼可以參考,常有大師就不寫.cpp了,宣告與實作都寫在.h上
商業上,會把實作過程(部分或全部)隱藏在.cpp中,再把.cpp編譯成連結檔(.o)、元件庫(.dll)或執行檔(.exe)
另外也補充C++11上超好用的thread_local,和C#相似,宣告與建立執行緒安全的記憶體空間
//宣告
class FileLogger
{
public:
static thread_local int MsgLen;
};
//實作(建立並初始化)
thread_local int FileLogger::MsgLen = -1;
之後補充其他更複雜的範例