[英]Win32 programming TextOut WM_Paint
Having some trouble in this block of code at the TextOut line it says: 在TextOut行的这段代码中遇到了一些麻烦,它说:
error: cannot convert 'std::string* {aka std::basic_string<char>*}' to
'LPCSTR {aka const char*}' for argument 4 to
'BOOL TextOutA(HDC, int, int, LPCSTR, int)'
I've searched for a while and wasn't able to find anything that didn't either eternally confuse me or would accomplish what I want to do which is draw a string. 我搜索了一阵子,却找不到任何不会使我永远困惑或无法完成我想做的事情的事情,那就是画一条线。
case WM_PAINT:
{
HDC hdc;
PAINTSTRUCT ps;
string text = "Something";
RECT rect;
GetClientRect( hwnd, &rect );
hdc = BeginPaint( hwnd, &ps );
TextOut( hdc, rect.right/2, rect.bottom/2, &text, 1 );
EndPaint( hwnd, &ps );
}
return 0;
break;
You need to pass a pointer to a char array, not a C++ string. 您需要传递一个指向char数组的指针,而不是C ++字符串。 Try:
尝试:
TextOut( hdc, rect.right/2, rect.bottom/2, text.c_str(), 1 );
Note that you've requested it to output only one character. 请注意,您已要求它仅输出一个字符。
The error message explains what the problem is: 错误消息说明了问题所在:
The LPCSTR
type is a typedef (alias for) const char *
. LPCSTR
类型是const char *
的typedef(别名)。 This is a C-style pointer, which is what the constant string "Something"
defaults to (but not text
). 这是C风格的指针,这是常量字符串
"Something"
默认为的值(而不是text
)。
The std::string
type is a typedef (alias for) std::basic_string<char>
. std::string
类型是std::basic_string<char>
的typedef(别名)。 This is a C++ template class that is used to manage strings dynamically, like C#/Java strings, or the CString
type from MFC/ATL. 这是一个C ++模板类,用于动态管理字符串,例如C#/ Java字符串或MFC / ATL中的
CString
类型。
The &text
line is a pointer to the string object, not a pointer to the string itself. &text
行是指向字符串对象的指针,而不是指向字符串本身的指针。 Likewise, std::string
does not provide implicit conversion to const char *
. 同样,
std::string
不提供对const char *
隐式转换。 You need to explicitly call text.c_str()
which is intended for use with APIs that take C-style strings. 您需要显式调用
text.c_str()
,该text.c_str()
旨在与采用C样式字符串的API一起使用。
For the last argument of TextOut
, you can pass -1
to get it to calculate the length of the string (not 1
). 对于
TextOut
的最后一个参数,您可以传递-1
以获取它来计算字符串的长度(而不是1
)。 Alternatively, as you have the string in a std::string
object, you can use text.size()
. 另外,当字符串在
std::string
对象中时,可以使用text.size()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.