2013-07-06 75 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。 –

相关问题