2

指示是:

MyString 对象应重载以下运算符:

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] == '\0')
    {
            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] == '\0')
    {
            exit(1);
    }
    else
    {
            return String[i];

    }
 }

我如何将其转换为重载的 () 运算符函数?我得到的最多的是:

 MyString& MyString::operator()(const int index, const char b)
 {
    if(String[index] == '\0')
    {
            exit(1);
    }
    else
    {

            String[index] = b;
    }


}


char& MyString::operator()(const int i)
{

    if( String[i] == '\0')
    {
            exit(1);
    }
    else
    {
            return String[i];

    }
}

我究竟做错了什么?

4

2 回答 2

3

您的边界检查是错误的,但您已经在原始代码中遇到了这个问题。

您的index参数神秘地将 type 从 更改intconst MyString&,这看起来是错误的。

于 2012-04-28T20:10:34.020 回答
2

Get 和 Set 以及 () 运算符的两个重载都以不适当(错误!)的方式检查字符串错误。请注意,如果字符串不是那么长,则字符串的第 i 个或第 n 个元素不能是 '\0'。如果您尝试读取超出当前字符串长度的内存,您可能会遇到读取访问冲突。

相反,您应该检查给定的索引是否小于字符串的长度,如果是,则返回该元素。否则,超出范围。

另一件事是,在 () 运算符的第一次重载中,您使用的是字符串对象来取消引用字符串数组,这没有多大意义。此外, b 应该是一个字符,而不是字符串,因为您只设置一个元素。

于 2012-04-28T20:13:42.457 回答