我想为一个名为Dictionary.With的类重载operator =,这些属性:
private:
char *language;
int noWords;
bool isOnline;
Word *v;
Word是另一个具有这些属性的类:
public:
char *value;
char type[20];
int noChars;
static int noWords;
这就是我想要为类Dictionary:
重载operator =的方法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);
}
}
我收到错误:&#34; Acces违规写入位置&#34;并将我重定向到这一行:
this->v[i].noChars = x.v[i].noChars;
我应该改变什么?我不能使用字符串。只需告诉我使用相同格式修改的内容。
P.S。:我可以在默认构造函数中执行此操作:
this->v = NULL;
答案 0 :(得分:0)
你真的应该考虑使用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);
}
}