2011-11-27 118 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。