运算符 = 过载的问题
Operator = problems to overload it
我想重载名为 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);
}
}
相关文章:
- 一个关于在C++中重载布尔运算符的问题
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 运算符继承和 cpp 核心准则 c.128 的问题
- 在C++中使用重载提取运算符时出现问题
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 关于条件块的问题与&&运算符有关
- 重载运算符与添加问题
- 加、乘、除、减复数的问题 C++ - 运算符重载
- 我需要这方面的帮助C++在使用逻辑运算符时是/否问题
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 如何解决不明确的运算符过载问题?
- 屏幕插入运算符<<的运算符过载问题
- 如何通过使用 2 位或更多数字的 XOR 运算符来执行此操作C++问题
- 在 C++ 的自定义运算符中删除与删除[](不同于常见的删除与删除[]问题)
- 用户定义的文本运算符(在原始模式下)存在问题
- 关于重载 -> 运算符中 const 关键字的特定位置的问题
- 字符 * 未从重载运算符或内存管理问题正确返回
- constexpr 运算符重载使用参数的问题
- c++中重载输入运算符的问题
- 有趣的问题运算符重载