运算符 = 过载的问题

Operator = problems to overload it

本文关键字:问题 运算符      更新时间:2023-10-16

我想重载名为 Dictionary 的类的运算符 =。使用以下属性:

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

Word 是具有这些属性的另一个类:

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

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

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);
    }
}

收到错误:"访问违规写入位置"并将我重定向到此行:

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

我应该更改什么?我不能使用字符串。只需告诉我使用相同的格式要修改什么。

PS:我可以在默认构造函数中执行此操作吗:

        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);
    }
}