如何访问STL字符串类中的成员变量?

8 c++ string class

我正在编写"开始使用C++早期对象"第7版中的一个编程挑战,其中一个分配要求创建一个派生自STL字符串类的类.我发布的问题是为了理解我被允许做什么,以及我应该如何实施解决方案,以便没有人提供更高级的建议.

- 问题,因为它写在文本中 -

回文测试

Palindrome是一个向前读取相同的字符串.例如,妈妈,爸爸,女士雷达这些词都是回文.写一个class Pstring派生自STL string class.在Pstring class增加了一个成员函数

bool isPalindrome()
Run Code Online (Sandbox Code Playgroud)

确定该字符串是否是回文.包含一个构造函数,该构造函数将STL string对象作为参数并将其传递给字符串基类构造函数.通过主要程序测试您的类,该程序要求用户输入字符串.程序使用字符串初始化Pstring对象,然后调用isPalindrome()来确定输入的字符串是否是回文.

您可能会发现使用字符串类的下标operator []很有用:如果str是一个字符串对象而k是一个整数,则str [k]返回字符串中位置k的caracter.

- 结束 -

我的主要问题是如何访问保存我的字符串对象的成员变量,如果我从派生Pstring的类是一个我没写的类,我不知道它是如何实现其成员的?

例如,

#include <string>
using namespace std;

class Pstring : public string
{
public:
  Pstring(std::string text)
   : string(text) { }

  bool isPalindrome()
  {
    // How do I access the string if I am passing it to the base class?

    // What I think I should do is...
    bool is_palindrome = true;
    auto iBegin = begin();
    auto iEnd   = end() - 1;

    while (iBegin < iEnd && is_palindrome)
    {
      if (*iBegin++ != *iEnd--)
        is_palindrome = false;
    }

    return is_palindrome;

    // But I think this is wrong because...
    // #1 The book did not discuss the keyword auto yet
    // #2 The book discussed when a class is derived from another class,
    //    how the members from super class will be accessible to the sub class.
    //    However, with this assignment, I don't see how to access the members.
  }
}
Run Code Online (Sandbox Code Playgroud)

我觉得我这样做不正确的原因是因为赋值使用下标表示法,但是,如果我不知道存储字符串的变量的名称,我不明白如何使用下标表示法.

任何帮助将不胜感激,因为作者不提供解决方案,除非我是一名在我看来相当蹩脚的教练.这可能与这是学术文本这一事实有关.

Pub*_*bby 3

您不应该继承 std::string,因为它不是为此设计的,您也不需要继承来查找回文。

请参阅:继承和重写 std::string 的函数?

回文解决方案(来自这个问题:Check if a string is palindrome链接自此:C++ Palindrome finder optimization

#include <algorithm>

bool isPal(const string& testing) {
    return std::equal(testing.begin(), testing.begin() + testing.size() / 2, testing.rbegin());
}
Run Code Online (Sandbox Code Playgroud)

那本书的质量似乎有问题。自由函数(取决于你问的是谁)几乎总是优于成员函数,尤其优于继承。


如果必须使用继承:

class Pstring : public string
{
    //...

    bool isPalindrome()
    {
      return std::equal(begin(), begin() + size() / 2, rbegin());

      // as a side-note, 'iterator' will refer to the inherited return type of begin()
      // Also, 'operator[](x)' will call the subscript operator
    }
};
Run Code Online (Sandbox Code Playgroud)