重载 Set() 和 Get() 的括号运算符

overloading parenthesis operator for Set() and Get()

本文关键字:运算符 Set 重载 Get      更新时间:2023-10-16

说明是:

对象应重载以下运算符:

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 应该是那里的字符,而不是字符串,因为您只设置了一个元素。