C++为什么const LPSTR与const char*不同?

soo*_*qua 2 c++

为什么以下代码编译?

void foo(const LPSTR str) {
    str[0] = '\0';
}
Run Code Online (Sandbox Code Playgroud)

void foo(LPCSTR str) {
    str[0] = '\0';
}
Run Code Online (Sandbox Code Playgroud)

void foo(const char* str) {
    str[0] = '\0';
}
Run Code Online (Sandbox Code Playgroud)

才不是.

它实际上LPTSTR在我的代码中,因此const版本是LPCTSTR......所以我可以通过拥有类似的东西来提高代码的可读性const LPTSTR,或者它必须是LPCTSTR或者const TCHAR*

Rei*_*ica 7

typedef从外部修改"密封"该类型.LPSTR是一个char *时期.添加const到(as const LPSTR)会const增加到外部:你得到一个char * const.

你想要的是"注入" const(将它应用于指针,而不是指针),这是通过带有typedef的简单声明语法实现的.所以必须是LPCSTR,为这个目的创建的typedef.