The instructions are to:
The MyString object should overload the following operators:
1)Parenthesis operator should be overloaded to replace the Set and Get functions of your previous assignment. Note that both instances should issue exit(1) upon violation of the string array bounaries.
My .cpp file where the functions are defined:
// 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];
}
}
How do I possibly transform this into an overloaded () operator function?? The most I’ve gotten is:
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];
}
}
What am I doing wrong?
Both Get and Set, and the two overloads of the () operator check for out of string error in an inappropriate (wrong!) manner. See, the i-th, or n-th element of a string can not be ‘\0’ if the string is not that long. If you try to read memory beyond the current string length, you will probably get a read access violation.
Instead, you should check whether the given index is less then the string’s length, and if it is, then return the element. Otherwise, it is out of bounds.
Another thing is that in the first overload of the () operator, you are using a string object to dereference a string array, which doesn’t make much sense. Also, b should be a character there, not a string, since you are setting only one element.