【问题标题】:String class using linked list使用链表的字符串类
【发布时间】:2014-06-18 02:55:15
【问题描述】:

我必须编写这个使用链表表示的 String 类。我的复制构造函数似乎有问题,我不知道如何编写赋值运算符。知道错误在哪里以及如何编写它们吗?所示代码适用于具有以下操作 String s="word" 的复制构造函数。我不确定如何为 String s1=s2 写一个。到目前为止,这是我的代码:


struct Element
{
char data;
Element* next;
};
class String
{
   Element* top;
public:
   String();
   bool empty() const;
   char last() const;
   char pop();
   void push(char);
   friend std::ostream& operator<<(std::ostream&, const String&);
   friend std::istream& operator>>(std::istream&, String&);
   String(const char*);
};

String::String(const char *p)
{
    int l = strlen(p);
    for(int i=0; i < l+1 ; i++)
    {
        Element *newElement;
        newElement = new Element;
        newElement->data = p[i];
        newElement->next = NULL;
        if(top == NULL)
        {
            top = newElement;
        }
        else
        {
            Element *tmp = top;
            while(tmp->next != NULL)
            {
                tmp = tmp->next;
                tmp->next = newElement;
            }
        }
    }
}

int main()
{
String s="Hello";
std::cout<<s;//operator<< works tested it
}

【问题讨论】:

  • 包括您看到的错误以及您为解决问题所做的工作将很有用。
  • @brader24 我没有收到错误,但程序崩溃了。
  • @user3144334 - I don't get an error but the program crashes 你没有发布程序——你只是发布了一个课程。没有赋予它生命的东西,一个班级就无法生存。请发布一个重复错误的 main() 函数。
  • newElement->data 是什么类型?您的 while 循环看起来也错误,您将 newElement 分配给列表中的每个 Element 实例。
  • @user3144334 - 请发布Element 课程。此外,您发布的代码中没有复制构造函数。 String(const String&amp;) 函数在哪里?

标签: c++ linked-list copy-constructor assignment-operator


【解决方案1】:

如果你定义了单链表,那么在链表的头部而不是尾部添加新元素要好得多。不过,您的功能可能如下所示

字符串::字符串(const char*p) { 对于 ( ; *p; ++p ) { 元素 *newElement = 新元素; 新元素->数据 = *p; 新元素->下一个 = NULL; 如果(顶部 == NULL) { 顶部 = 新元素; } 别的 { 元素 *tmp = 顶部; 而 ( tmp->next != NULL ) temp = tmp->next; tmp->下一个=新元素; } } }

顺便说一句,它不是复制构造函数。至于复制构造函数则可以定义为

String::String( const String &s ) : top( NULL ) { 如果(停止) { 顶部 = 新元素; 顶部->数据 = s.top->数据; 顶部->下一个 = NULL; for ( 元素 *tmp1 = top, tmp2 = s.top; tmp2->next; tmp1 = tmp1->next, tmp2 = tmp2->next) { tmp1->next = 新元素; tmp1->下一个->数据 = tmp2->下一个->数据; tmp1->下一个->下一个 = NULL; } } }

【讨论】:

    【解决方案2】:

    在以下代码中,您的 while 循环将永远不会执行,因为 top-&gt;next 将是 NULL

    Element *tmp = top;
    while(tmp->next != NULL)
    {
        ...
    }
    

    此外,正如@Claptrap 所评论的,您在每次循环迭代时分配newElement

    考虑到这一切,我不明白它为什么会失败,但它可能是在你没有发布的代码中。请尝试将您的代码减少到重现问题所需的最低限度,然后将该代码包含在您的帖子中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2016-07-23
      • 2011-05-19
      • 1970-01-01
      相关资源
      最近更新 更多