运算符 = 重载它的问题

Operator = problems to overload it

我想为名为 Dictionary.With 的 class 重载运算符 = 这些属性:

private:
char *language;
int noWords;
bool isOnline;
Word *v;

Word 是另一个 class,具有以下属性:

public:
char *value;
char type[20];
int noChars;
static int noWords;

这就是我想为 class 字典重载运算符 = 的方式:

void operator=(Dictionary x)
{
    this->language = new char[strlen(x.language)+1];
    strcpy(this->language,x.language);
    this->noWords = x.noWords;
    this->isOnline = x.isOnline;
    for (int i = 0; i < noWords; i++)
    {

        this->v[i].noChars = x.v[i].noChars;
        strcpy(this->v[i].type, x.v[i].type);
        this->v[i].value = new char[strlen(x.v[i].value) + 1];
        strcpy(this->v[i].value, x.v[i].value);

    }
}

我收到错误:"Acces violation writing location" 并将我重定向到这一行:

this->v[i].noChars = x.v[i].noChars;

我应该改变什么?我不能使用字符串。直接告诉我用同样的格式修改什么就可以了

P.S.: 我可以在默认构造函数中这样做吗:

        this->v = NULL;

?

你真的应该考虑使用 std::vector 和 std::string 而不是使用 new[] 进行分配并直接管理数据。

试试这个:

void clear()
{
    if( language )
    {
        delete[] language;
        language = 0;
    }
    for( int i = 0; i < noWords; ++i )
        delete[] v[i].value; 
    delete[] v;
    v = 0;
}

void operator=(Dictionary x)
{
    // You really should deallocate any old value to avoid a memory leak
    clear();
    this->language = new char[strlen(x.language)+1];
    strcpy(this->language,x.language);
    this->noWords = x.noWords;
    this->isOnline = x.isOnline;
    this->v = new Word[noWords];
    for (int i = 0; i < noWords; i++)
    {
        this->v[i].noChars = x.v[i].noChars;
        strcpy(this->v[i].type, x.v[i].type);
        this->v[i].value = new char[strlen(x.v[i].value) + 1];
        strcpy(this->v[i].value, x.v[i].value);

    }
}