【问题标题】:Class derived from string从字符串派生的类
【发布时间】:2015-07-05 13:26:51
【问题描述】:

我有一个问题,我不知道从这里去哪里。

在这个程序中,您将创建一个名为 mystring 的类,它是从类派生的 细绳。类 mystring 应包括:

  • 一个私有数据成员id,是一个整数,代表一个字符串的ID(见函数main()中的例子)。

  • 一个公共方法,构造函数mystring(int, char *),它有两个 参数:一个整数 (int) 和一个字符串 (char *)。它应该(1)调用基类 使用字符串参数 (char *) 和 (2) 分配整数参数 (int) 的构造函数 到身份证。

  • 一个公共方法int getid(),它返回类mystring的id。

这就是我目前所拥有的

class mystring : public string
{
  private:
    int id;
  public:
    mystring(int id, char *words);
    int getid();
};

mystring::mystring(int id, char *words)
{
  string a (words);
  this->id = id;
}

int mystring::getid()
{
  return id;
}

// If your class is implemented correctly, the main program should work as
//the followings
int main()
{
  mystring x(101, "Hello Kitty");   // “hello Kitty” has an ID 101
  cout << x.getid() << endl;            //display 101
  cout << x << endl;                    //display string value: “Hello Kitty”
  cout << x.length() << endl;       //display length of the string: 11
  return 0;
}

我明白了

101

0

【问题讨论】:

    标签: c++ string class derived


    【解决方案1】:

    在您的构造函数中,您没有为您的实例调用 std::string 基本构造函数,您只是创建了一个本地字符串,然后将其丢弃。

    改变这个:

    mystring::mystring(int id, char *words)
    {
        string a (words); //creates a local string called a
        this->id = id;    //initializes id
    }
    

    要使用初始化列表,如下所示:

    mystring::mystring(int id, char *words) :
        string(words), //calls the string base constructor
        id(id)         //initializes id
    {}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      相关资源
      最近更新 更多