【问题标题】:Overloading [] in subclassed C++ string在子类 C++ 字符串中重载 []
【发布时间】: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


【解决方案1】:

虽然观察到您在这里所做的事情是不必要的,但语法如下:

return string::operator[](index);

您正在呼叫您的 string 父级的 operator[]。这应该比使用c_str 更可取,因为string::operator[] 在调试版本中进行边界检查。

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

对于第一个问题,没有。抛出异常后,您不需要返回语句。事实上,如果你这样做了,编译器可能会警告你“无法访问的代码”。

【讨论】:

  • 事实上,正确的实现(尽可能多的废话可以正确实现)只需{ return string::at(index); }
【解决方案2】:

首先,不推荐从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);
 }

【讨论】:

  • I tried return this[index] 这就是我所指的。
【解决方案3】:

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

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

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

【讨论】:

    【解决方案4】:

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

    return this->c_str()[index];
    

    【讨论】:

      猜你喜欢
      • 2012-09-24
      • 2013-08-10
      • 1970-01-01
      • 2015-06-04
      • 2015-10-22
      • 2013-03-07
      • 2015-03-27
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多