【发布时间】:2015-02-27 22:28:32
【问题描述】:
什么是我返回这里合适的事情?
char BCheckString::operator[](int index)
{
if (index < 0 || this->length() <= index)
{
throw IndexOutOfBounds();
???Do I need to return something here???
}
else
{
return ?????;
}
}
我尝试了return this[index],但 VS2013 说:“不存在从“BCheckString”到“char”的合适转换函数。我不知道抛出后返回什么。
我有:
class BCheckString : public string
{
private:
bool checkBounds();
public:
BCheckString(string initial_string);
char operator[](int index);
class IndexOutOfBounds{};
};
和
BCheckString::BCheckString(string initial_string) : string(initial_string)
{
}
char BCheckString::operator[](int index)
{
if (index < 0 || this->length() <= index)
{
//throw IndexOutOfBounds();
cout << "index out of bounds" << endl;
return 'A';
}
else
{
return 'A';
}
}
显然这是家庭作业;)
【问题讨论】:
-
你为什么公开从
std::string派生? stackoverflow.com/questions/6006860/… -
@PaulMcKenzie 上帝保佑我们。老师告诉他们的学生从那些不是被设计成派生的类中派生出来。这就是为什么大多数软件都搞砸了。
-
无论如何,我在这里看到的答案将帮助您解决问题。我建议你也从“Effective C++”中引用解释为什么你不应该从
std::string派生的引文,并将它展示给你的老师(在你理解之后)。 -
确实,我想知道如果将 std::string 更改为 "final" 会破坏多少糟糕的代码。
标签: c++ string operator-overloading subclassing