Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ “为什么我不能打印”;第一个“;?_C++_Printing_Linked List_Operator Overloading - Fatal编程技术网

C++ “为什么我不能打印”;第一个“;?

C++ “为什么我不能打印”;第一个“;?,c++,printing,linked-list,operator-overloading,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

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

这是我的密码:

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

问题在于你的构造函数。您将
head
初始化为null,将
head
的值复制到
h
(在本例中为null),将
h
分配到一个新的
ListNode
,但决不将
head
指针重新分配到
ListNode
所指向的
ListNode>

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;
    }
}

问题在于你的构造函数。您将
head
初始化为null,将
head
的值复制到
h
(在本例中为null),将
h
分配到一个新的
ListNode
,但决不将
head
指针重新分配到
ListNode
所指向的
ListNode>

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;
    }
}

查看类的定义和列表可能会有所帮助node@kcraigie无论如何,感谢你的时间。非常感谢。查看类的定义和列表可能会有所帮助node@kcraigie无论如何,感谢你的时间。非常感谢。