【发布时间】:2012-04-28 20:03:28
【问题描述】:
指令是:
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];
}
}
我做错了什么?
【问题讨论】:
-
什么不正常?你得到一个编译错误?运行时崩溃?
-
这将是 akward 使用。你会喜欢
b(1,5);operator[] 来达到同样的目的。 -
这是我收到的错误之一错误:在â((MyString*)this)->MyString::String[index]â 中不匹配âoperator[]â ??
标签: c++ string object operator-overloading