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无论如何,感谢你的时间。非常感谢。