2011-11-27 71 views
2

如果我有#define GAMENAME "POSEIDON"並希望將其轉換爲LPCSTR或std :: string,我該如何執行「正確」操作?#define字符串強制轉換爲LPCSTR或std :: string

外匯:

m_hwnd = CreateWindowEx(NULL, 
    "GLClass", 

    /* My GAMENAME #define goes here */ 
    (LPCSTR)GAMENAME, 

    dwStyle | WS_CLIPCHILDREN | 
    WS_CLIPSIBLINGS, 
    /* The X,Y coordinate */ 
    0, 0, 
    m_windowRect.right - m_windowRect.left, 
    m_windowRect.bottom - m_windowRect.top, 
    /* TODO: Handle to Parent */ 
    NULL, 
    /* TODO: Handle to Menu */ 
    NULL, 
    m_hinstance, 
    this); 

也許我只是走個不錯的辦法這樣做呢?

+0

你如何將它用作'std :: string'? – kennytm

+0

'std :: string thisString = GAMEWORLD;類 - >構件(thisString.str())';我可以將它轉換爲定義中的LPCSTR:#define GAMENAME((LPCSTR)「POSEIDON」)'但我希望它在#define中是通用的 – krslynx

回答

1

#defines由preprocessor處理,所以GAMENAME在你的程序中並不是一個真正的變量。使用演員表演解決你自己的問題的答案似乎會使問題變得更糟。 Mike Dunn在Code Project的字符串上的第二個article解釋了爲什麼演員不是最好的選擇。 first article也值得一讀。

您應該能夠創建的std :: string這樣的:

std::string str = "char string"; 

然後從它創建LPCSTR:

LPCSTR psz = str.c_str(); 

在你的程序中,您會通過PSZCreateWindowEx()。另一個值得思考的問題是遊戲名稱是否真的需要改變?如果不是這樣,最好讓它保持不變。

1
// Instead of a macro use a template called 'GAMENAME'. 
template <typename T> T GAMENAME() { return T("POSEIDON"); }; 

使用例:

GAMENAME<LPCSTR>(); 
GAMENAME<std::string>(); 

希望這有助於。

1

#define s僅由預處理器用於搜索和替換源代碼中使用的定義的標記。因此,任何你有GAMENAME的地方,在之前會被字面上的"POSEIDON"取代,編譯器甚至會針對你的源代碼運行。

真的,儘管如此,在C++中使用最好的東西將是一個static const變量。這將爲您的代碼提供更多的描述性含義,同時避免預處理器宏的缺陷。這樣做的最大的「缺點」是,你得把你靜態的(非整數)定義在一個翻譯單元,以及頭文件:

// my_class.h 
class MyClass { 
public: 
    static const char *kGameName; 

    MyClass(const RECTANGLE &rect) m_windowRect(rect) { 
     CreateWindow(); 
    } 

private: 
    HANDLE m_hwnd; 
    RECTANGLE m_windowRect; 
    HINSTANCE m_hinstance; 
}; 

// my_class.cpp 
const char *MyClass::kGameName = "POSEIDON"; 

void MyClass::CreateWindow() { 
    m_hwnd = CreateWindowEx(NULL, 
     "GLClass", 

     /* My GAMENAME constant is used here */ 
     kGameName, 

     dwStyle | WS_CLIPCHILDREN | 
     WS_CLIPSIBLINGS, 
     /* The X,Y coordinate */ 
     0, 0, 
     m_windowRect.right - m_windowRect.left, 
     m_windowRect.bottom - m_windowRect.top, 
     /* TODO: Handle to Parent */ 
     NULL, 
     /* TODO: Handle to Menu */ 
     NULL, 
     m_hinstance, 
     this); 
} 

如果你想使用std::string剛剛替換在那裏我使用char *並在CreateWindowEX調用中使用kGameName.c_str()

順便提一下,LPCSTR基本上是一個#DEFINE LPCSTR const char*

0

LPCSTR =長指向常量字符串,其被定義爲一個const char*(即一個C-字符串)。 "POSEIDON"是一個字符串文字,其類型爲const char*(即LPCSTR)。

  1. 你可以保留原樣,然後當你需要一個std::string構建一個這樣的:

    std::string myString(GAMENAME); 
    

    或者創建一個臨時std::string對象(如果std::string不會自動從一個char*構建時它的需要):

    std::string(GAMENAME) 
    
  2. 你可以有一個const std::string GAMENAME = "POSEIDON";,然後無論你ñ請使用由GAMENAME.c_str()返回的LPCSTR。

相關問題