2011-04-24 109 views
2

我正在C++/CLI中構建一個項目,其中我必須在其中一個窗體中顯示一個消息框。內容必須是std :: string和int的組合。MessageBox中需要C++/CLI幫助::顯示

但我無法得到正確的語法。

我試過如下:

std::string stringPart = "ABC"; 
int intPart = 10; 
MessageBox::Show("Message" + stringPart + intPart); 

我也試過:

String^ msg = String::Concat("Message", stringPart); 
msg = String::Concat(msg, intPart); 
MessageBox::Show(msg); 

是否有人可以幫助我的語法。

謝謝。

+0

你什麼錯誤,或者是你有什麼問題? – 2011-04-24 17:23:24

+0

http://social.msdn.microsoft.com/Forums/en-US/d70a77b7-1508-4884-a5bc-106cf068b1be/how-can-i-show-messagebox-in-visual-c?forum=vcgeneral – 2014-02-07 13:26:22

回答

8

您的問題是std::string是非託管的,不能分配到託管System::String。解決方案是編組。看到這個MSDN頁:http://msdn.microsoft.com/en-us/library/bb384865.aspx

因此,這裏的解決方案(適用於Visual Studio):

#include <msclr/marshal_cppstd.h> 

// ... 

std::string stringPart = "ABC"; 
int intPart = 10; 

String^ msg = String::Concat("Message", msclr::interop::marshal_as<System::String^>(stringPart)); 
msg = String::Concat(msg, intPart); 
MessageBox::Show(msg); 
+2

也許它已經太晚了,但沒有必要進行修剪。 'System :: String'有一個構造函數,它接受'const char *'或'const wchar_t *',所以解決方案很簡單:'String^msg = gcnew System :: String(stringPart.c_str());'' – Quest 2016-08-29 14:44:10