C ++重载+ =带双指针的运算符

时间:2015-04-29 14:44:32

标签: c++ pointers operator-overloading

所以我试图重载+ =运算符以进行字典程序分配。 这是我的功能:

Definition& Definition::operator += (const String& input) {
    String** temp;
    temp = new String*[numDefs + 1];
    temp[0] = new String[numDefs];
    for (int i = 0; i < numDefs; i++)   {
            temp[i] = def[i];
    }
    temp[0][numDefs] = input;
    delete[] def;
    def = temp;
    numDefs++;
    return *this;
}

然而,当我尝试将'输入'放入'temp'时,它似乎不起作用。这是我用于将字符串分配给字符串的String类函数:

String& String::operator=(const String& input) {
    data = NULL;
    (*this) = input.getData();
    return *this;
}

String& String::operator=(const char* input) {
    if (data != input)
    {
        if (data != NULL)
        {
            delete[] data;
            data = NULL;
        }
        data_len = strSize(input);
        if (input != NULL)
        {
            data = new char[data_len + 1];
            strCopy(data, input);
        }
    }
    return *this;
}

似乎无法找到问题。

1 个答案:

答案 0 :(得分:1)

一分钟前发布的答案是用户删除并帮助了我,我将代码更改为:

Definition& Definition::operator += (const String& input) {
    String** temp;
    int tempSize = numDefs + 1;
    temp = new String*[tempSize];
    for (int i = 0; i < numDefs; i++)   {
        temp[i] = new String;
        temp[i] = def[i];
    }
    temp[numDefs] = new String;
    (*temp[numDefs]) = input;
    delete[] def;
    def = temp;
    numDefs = tempSize;
    return *this;
}

无论是谁,谢谢!