c++ - 为什么我不能打印 "first"?

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

我使用链表来存储我的数据。构造函数和打印函数好像没问题,就是不知道是不是我的指针出错了。

这是我的代码:

#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可以打印出来,但是我的“第一”不见了。

最佳答案

问题出在你的构造函数上。你初始化 head为空,复制 head 的值至 h (在这种情况下为 NULL),分配 h指向新的 ListNode但永远不要重新分配 head指向 ListNode 的指针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;
    }
}

关于c++ - 为什么我不能打印 "first"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33471097/

相关文章:

c++ - 寻求 DDX 的替代品

c++如何根据最后一个 '.'将字符串拆分为两个字符串

c++ - 这个具有类似流程控制关键字的标识符的构造是什么?

php - 按顺序打印网页

c++ - 带有节点迭代器的链表构造函数给出无效指针的错误

java - 如何将从堆栈弹出的 ArrayList 的类型从对象更改为链表?

c++ - GtkSpinButton 是否能够设置时间间隔?

iOS - 收到警告但无法打印

windows-7 - 无法使用 Windows 命令提示符打印双字节字符

c++ - 运算符 [] 是否接受 C++ 中除整数以外的类型?