【问题标题】:Why I cannot print "first"?为什么我不能打印“第一”?
【发布时间】:2016-02-01 22:50:03
【问题描述】:

我使用链表来存储我的数据。构造函数和打印函数似乎很好,我只是不知道我的指针是否出错。

这是我的代码:

#include <iostream>   
using namespace std;

///constructor
String::String( const char * s): head(NULL)
{
    ListNode * h = head;
    h = new ListNode(s[0], NULL);
    ListNode * c = h;
    for(int i = 1; s[i] != '\0'; ++i)
    {
        c->next = new ListNode(s[i], NULL);
        c = c->next;
    }
}
// redefine the << operator
ostream & operator << ( ostream & out, String str )
{
    str.print(out);
    return out;
}
istream & operator >> ( istream & in, String & str )
{
    str.read(in);
    return in;
}
void String::print( ostream & out )
{
    ListNode * c = head;
    for(; c != '\0'; c = c->next)
        {out << c->info;}
}
void String::read( istream & in )
{
    ListNode * c = head;
    for(; c != '\0'; c = c->next)
        in >> c->info;
}
int main()
{
    cout << "123" << endl;
    String firstString("First");
    cout << firstString << endl;
    cout << "1234" << endl;
    cout << "12345" << endl;
    return 0;
}

我的结果是

123

1234
12345

连线我的123和1234 12345可以打印出来,但是我的“第一个”消失了。

【问题讨论】:

  • 查看类的定义和列表节点可能会有所帮助
  • @kcraigie 无论如何感谢您的时间。谢谢!

标签: c++ printing linked-list operator-overloading


【解决方案1】:

问题是你的构造函数。您将head 初始化为null,将head 的值复制到h(在这种情况下为NULL),分配h 以指向新的ListNode,但永远不要将head 指针重新分配给@987654327 @ 由h 指向。

String::String( const char * s): head(NULL)
{
    head = new ListNode(s[0], NULL);
    ListNode * c = head;
    for(int i = 1; s[i] != '\0'; ++i)
    {
        c->next = new ListNode(s[i], NULL);
        c = c->next;
    }
}

【讨论】:

    猜你喜欢
    • 2020-07-05
    • 2014-02-28
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多