在子类C ++字符串中重载[]

时间:2015-02-27 22:28:33

标签: c++ string operator-overloading subclassing

回到这里对我来说什么是正确的?

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说:&#34;没有合适的转换函数来自&#34; BCheckString&#34;到&#34; char&#34;存在。而且我不知道在投掷之后该返回什么。

我有:

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';
    }
}

显然这是家庭作业;)

4 个答案:

答案 0 :(得分:3)

虽然观察你在这里所做的事情是不必要的,但语法却是:

return string::operator[](index);

您正在呼叫operator[]父母的string。这应该优先于使用c_str,因为string::operator[]确实限制了在调试版本中的检查。

还值得注意的是.at已经在发布版本中检查边界,并抛出std::out_of_range

对于第一个问题,没有。抛出异常后,您不需要返回声明。事实上,如果你这样做,编译器可能会警告你关于&#34;无法访问的代码&#34;。

答案 1 :(得分:3)

首先,不推荐从std::string派生:Why should one not derive from c++ std string class?

关于你的问题:

1)throw之后你没有返回任何东西。

2)您尝试使用operator[]不正确,因为您没有调用父类的std::string::operator[]

拨打正确的operator[]

 else
 {
    return std::string::operator[](index);
 }

答案 2 :(得分:2)

this是一个指针,因此this[index]会错误地将this视为指向要访问其中index个实例的实例数组。这将是类本身的一个实例,并且没有隐式转换为声明的返回类型char(这是错误消息所抱怨的内容)。

你需要从基本字符串中获取char,这是通过

完成的
return this->string::operator[](index);

答案 3 :(得分:1)

如果从std :: string派生,则可以使用c_str()方法访问数据。

return this->c_str()[index];