2013-07-06 76 views
2

我試圖做這樣的:如何將字符串添加到Windows窗體標籤?

this->Label1->Text = "blah blah: " + GetSomething(); 

哪裏GetSomething()是返回一個字符串的函數。

,編譯器給了我一個錯誤:

"error C2679: binary '+' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)"

string GetSomething() 
{ 
    int id = 0; 
    string Blah[] = {"test", "fasf", "hhcb"}; 

    return Blah[id]; 
} 
+0

可以顯示GetSomething代碼? – billz

+1

您是否#include ? –

+0

@RanEldan我只是這樣做,另一個錯誤出現:\t錯誤C2664:'System :: Windows :: Forms :: ToolStripItem :: Text :: set':無法將參數1從'std :: basic_string <_Elem,_Traits ,_Alloc>'到'System :: String ^' – Kyle

回答

0

免責聲明:我不是一個 C++/CLI嚮導。

我相信你正在尋找的東西是這樣的:

String^ GetSomething() 
{ 
    Int32 id = 0; 
    array <String^>^ Blah = gcnew array<String^>{"test", "fasf", "hhcb"}; 
    return Blah[id]; 
} 

您試圖混合CLI和非CLI代碼。 Windows窗體使用CLI。請勿使用std::string。而是使用System::String(我的代碼假定您有using namespace System在你的代碼的頂部,你還會注意到,我把它換成intSystem::Int32的管理等同。

你的代碼的其餘部分是好的。我有放置調用GetSomething()在回調的按鈕:

private: 
System::Void Button1_Click(System::Object^ sender, System::EventArgs^ e) 
{ 
    this->Label1->Text = "blah blah: " + GetSomething(); 
} 
4

的問題是,你在遊戲中至少有兩個不同的字符串類在這裏

的WinForms(你正在使用顯然是爲您的GUI )使用.NET System::String class無處不在。因此,Label.Text屬性正在獲取/設置一個.NET System::String對象。

你說在GetSomething()方法返回一個std::string對象的問題。 std::string類基本上是C++的內置字符串類型,作爲標準庫的一部分提供。

這兩個類都很好,很好地服務於各自的目的,但它們不直接兼容。這是什麼(第二次嘗試的)編譯器的消息要告訴你:

error C2664: void System::Windows::Forms::Control::Text::set(System::String ^) : cannot convert parameter 1 from std::basic_string<_Elem,_Traits,_Ax> to System::String ^

用簡單的英語改寫:

error C2664: cannot convert the native std::string object passed as parameter 1 to a managed System::String object, required for the Control::Text property

事實是,你真的不應該將兩者混合字符串類型。由於WinForms基本上強制你的字符串類型,至少對於與GUI交互的任何代碼來說,這是我要標準化的一個。所以如果可能的話,重寫GetSomething()方法返回一個System::String對象;例如:

using namespace System; 

... 

String^ GetSomething() 
{ 
    int id = 0; 
    array <String^>^ Blah = gcnew array<String^>{"test", "fasf", "hhcb"}; 
    return Blah[id]; 
} 

... 

// use the return value of GetSomething() directly because the types match 
this->Label1->Text = "blah blah: " + GetSomething(); 

如果這是不可能的(例如,如果這是庫代碼有很少或沒有與你的GUI),那麼你需要explicitly convert one string type to the other

#include <string> // required to use std::string 

... 

std::string GetSomething() 
{ 
    int id = 0; 
    std::string Blah[] = {"test", "fasf", "hhcb"}; 
    return Blah[id]; 
} 

... 

// first convert the return value of GetSomething() to a matching type... 
String^ something = gcnew String(GetSomething().c_str()); 

// ...then use it 
this->label1->Text = "blah blah: " + something; 
+0

@Jan你也應該知道你在混合字符集和編碼。 .NET在大多數類中使用Unicode/UTF-16(尤其是System :: String),在某些類中使用Unicode/UTF-8(例如System.IO::Stream::StreamWriter(System:: String ^)) 。您的C++代碼使用ANSI代碼頁。當您「上轉換」爲Unicode時,您必須知道源ANSI代碼頁將被正確確定。當你從Unicode中「下轉換」時,你必須知道你需要哪個ANSI代碼頁並理解可能會丟失數據。您可以選擇儘可能使用C++中的Unicode。 –

相關問題