C ++ / cli operator =重载参考

时间:2017-05-03 11:58:19

标签: c++ .net operator-overloading c++-cli

我在c ++ / cli:

中遇到了重载operator =的问题
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

所以,我的问题是: 如何声明operator = overload来使用它:test2 =&#34; 123&#34 ;; ?

内置的String类如何能够像这样分配一个String:String ^ foo =&#34; 123&#34 ;; ?

1 个答案:

答案 0 :(得分:0)

@Dan你是对的,错误是在串口字节转换中:

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

我已将Text::Encoding::ASCII替换为Text::Encoding::Unicode 它工作正常。