2017-05-03 78 views
0

我不得不超負荷運營問題=在C++/CLI:C++/CLI運算符=過載基準

public ref class wString 
{ 
public: 
    wString(int length) 
    { 
     this->Bytes = gcnew array<Byte>(length); 
     this->Length = length; 
    } 
    Byte% operator[](int index) 
    { 
     return this->Bytes[index]; 
    } 
    wString^ operator+(wString^ wstr) 
    { 
     wString^ res = gcnew wString(this->Length + wstr->Length); 

     for (int i = 0; i < this->Length; i++) 
      res[i] = this->Bytes[i]; 
     for (int i = 0; i < wstr->Length; i++) 
      res[i + this->Length] = wstr[i]; 

     return res; 
    } 
    void operator=(String^ str) 
    { 
     array<Byte>::Resize(this->Bytes, str->Length); 
     this->Length = str->Length; 
     for (int i = 0; i < str->Length; i++) 
      this->Bytes[i] = str[i]; 
    } 

    void operator=(wString^ wstr) 
    { 
     array<Byte>::Resize(this->Bytes, wstr->Length); 
     this->Length = wstr->Length; 
     for (int i = 0; i < wstr->Length; i++) 
      this->Bytes[i] = wstr[i]; 
    } 

    void operator=(const char *str) 
    { 
     int length = sizeof(str); 

     array<Byte>::Resize(this->Bytes, length); 
     this->Length = length; 
     for (int i = 0; i < length; i++) 
      this->Bytes[i] = str[i]; 
    } 

public: 
    int Length; 
private: 
    array<Byte>^ Bytes; 
}; 

MyForm(void) 
{ 
    wString^ test1 = gcnew wString(); 
    wString^ test2 = gcnew wString(); 
    wString^ test3 = gcnew wString(); 
    String^ test4; 

    test4 = "123"; // no error because test4 is a native type String 

    test1 = "123"; // error 
    *test2 = test4; // works well call operator= overload 
    test2->operator=("123"); // works well call operator= overload 

    test3 = test1 + test2; // doesn't work, don't know what appens here 
    test2[0] = 4; // works well 

所以,我的問題是: 我怎樣才能申報操作=超負荷使用它像這樣:test2 =「123」; ?

那麼內建的String類如何能夠像這樣分配一個String:String^foo =「123」; ?

+1

你爲什麼要編寫所有這些代碼?已經有['marshal_as()'](https://msdn.microsoft.com/en-us/library/bb384865.aspx)來執行此操作。 –

+2

wString%運算符=(String^str)。和Array :: Resize()。不要忽視C4244警告。 System :: String在CLR中進行了大量*微調優化,您永遠無法關閉。不要這樣做。 –

+0

我不明白我如何使用marshal_as來實現unsigned char字符串?也許你可以給我一個例子嗎? – Grokiff

回答

0

@丹你是對的,錯誤是在串口字節轉換:

res = String::Concat(res, System::Text::Encoding::Unicode->GetString(bytesReceived, 0, bytes)); 

我已經Text::Encoding::Unicode 取代Text::Encoding::ASCII它工作正常。