![](/img/trans.png)
[英]cannot convert from 'std::vector<_Ty>' to 'std::vector<_Ty> &
[英]'MessageBoxA' : cannot convert parameter 2 from 'std::vector<_Ty>' to 'LPCSTR'
以下代码有效:
void CMyPlugin8::myMessageBox(std::string& myString)
{
myString = "Received the following string\n" + myString;
char * writable = new char[myString.size() + 1];
std::copy(myString.begin(), myString.end(), writable);
writable[myString.size()] = '\0'; // don't forget the terminating 0 "delete[] writable;"
int msgboxID = MessageBox(
NULL,
writable,
"Notice",
MB_OK
);
delete[] writable;
}
为了自动清理,我使用了以下信息: How to convert a std::string to const char* or char*? .
以下代码会引发错误:
void CMyPlugin8::myMessageBox(std::string& myString)
{
myString = "Received the following string\n" + myString;
std::vector<char> writable(myString.begin(), myString.end());
writable.push_back('\0');
int msgboxID = MessageBox(
NULL,
writable,
"Notice",
MB_OK
);
}
我收到此错误: “MessageBoxA”:无法将参数 2 从“std::vector<_Ty>”转换为“LPCSTR”
您不能像LPCSTR那样传递矢量,必须这样做。 采用:
&writable[0]
要么:
writable.data()
代替。 或者只是使用myString.c_str()
MessageBox
采用const char*
。 您无需为此先复制字符串。 只需使用c_str
:
void CMyPlugin8::myMessageBox(std::string& myString)
{
myString = "Received the following string\n" + myString;
int msgboxID = MessageBox(
NULL,
myString.c_str(),
"Notice",
MB_OK
);
}
请注意,我认为您的API很差:您正在修改传入的字符串的值。通常,调用者不会期望这样。 我认为您的函数应如下所示:
void CMyPlugin8::myMessageBox(const std::string& myString)
{
std::string message = "Received the following string\n" + myString;
int msgboxID = MessageBox(
NULL,
message.c_str(),
"Notice",
MB_OK
);
}
void CMyPlugin8::myMessageBox(const std::string& myString)
{
std::string message = "Received the following string\n" + myString;
int msgboxID = MessageBox(
NULL,
message.c_str(),
"Notice",
MB_OK
);
}
谢谢大家和@Falcon
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.