重载 Set() 和 Get() 的括号运算符
overloading parenthesis operator for Set() and Get()
说明是:
对象应重载以下运算符:
1)括号运算符应重载,以替换上一个赋值的 Set 和 Get 函数。注意 两个实例都应该在违反字符串数组赏金时发出 exit(1)。
我的.cpp定义函数的文件:
// My original set function to replace the character at the index passed in with the character passed in
void MyString::Set(int index, char b)
{
if(String[index] == ' ')
{
exit(1);
}
else
{
String[index] = b;
}
}
//original get function to get the character of the index passed in as argument
char MyString::Get(int i)
{
if( String[i] == ' ')
{
exit(1);
}
else
{
return String[i];
}
}
我如何将其转换为重载 () 运算符函数?我得到的最多的是:
MyString& MyString::operator()(const int index, const char b)
{
if(String[index] == ' ')
{
exit(1);
}
else
{
String[index] = b;
}
}
char& MyString::operator()(const int i)
{
if( String[i] == ' ')
{
exit(1);
}
else
{
return String[i];
}
}
我做错了什么?
你的边界检查是错误的,但你在原始代码中已经遇到了这个问题。
您的index
参数神秘地将类型从int
更改为const MyString&
,这看起来是错误的。
Get 和 Set 以及 () 运算符的两个重载以不适当(错误!)的方式检查字符串错误。看,如果字符串不那么长,字符串的第 i 或第 n 个元素不能是"\0"。如果尝试读取超出当前字符串长度的内存,则可能会遇到读取访问冲突。
相反,您应该检查给定索引是否小于字符串的长度,如果是,则返回元素。否则,它就超出了界限。
另一件事是,在 () 运算符的第一个重载中,您使用字符串对象来取消引用字符串数组,这没有多大意义。此外,b 应该是那里的字符,而不是字符串,因为您只设置了一个元素。
相关文章:
- 使用运算符调用 void 函数时出错<set>
- 重构使用动态强制转换的 std::set 的比较运算符
- 错误 C2676:std::set::const_iterator 没有运算符 + 函数?
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- 有什么理由不扩展 std::set 以添加下标运算符吗?
- 如何为 Set 创建运算符 []?
- g++ std::set 找不到运算符<为类定义
- 重载一对 <std::string, std::Set 的<<运算符>
- std::set 的重载运算符<让我感到困惑
- std::set 和 < 运算符重载的奇怪行为?
- 运算符< std::set 的重载
- 在 std::set 中使用运算符 != 作为运算符<是否安全?
- C++std::set Find函数重载==运算符
- 错误 C2679:二进制'=':找不到采用类型 'Set<ElemType>' 的右侧操作数的运算符
- set<>类,当我插入类时,它不接受我的<运算符
- 需要覆盖哪个运算符才能在C++代码中使用 std::set
- cilk_for 通过 std::set 缺少运算符-() 进行并行化的错误
- 重载 Set() 和 Get() 的括号运算符
- 标准重载运算符<:设置(英语:SET)
- 为什么 STL <set> 重载运算符<函数必须是常量函数?