这段代码的最后那条语句会出现内存不能读的异常,是不是我的链表有问题呢?#include <iostream.h>
#include <string.h>class parents 
{
public:
inline parents();
parents(char *str);
void virtual display();
static parents *pHead;
parents *pNext;
protected:
char string1[30];
public:
virtual ~parents();
};class child : public parents
{
public:
inline child();
child(char *, char *);
void virtual display();
private:
char string2[20];
public:
virtual ~child();
};parents *parents::pHead=0;parents::parents()
{
cout << "parents default construction" << endl;
}parents::~parents()
{
}parents::parents(char *str)
{
cout << "parents  construction" << endl;
strcpy(string1,str);
if ( pHead==NULL ) 
pHead=this;
else 
{ cout << "constrcuting link list" << endl;
child *pS;
pS=(child *)pHead;
while ( pS!= NULL ) pS=(child*)pS->pNext;
pS=(child*)this;
}
this->pNext=NULL;
}void parents::display()
{
cout << this->string1 << endl;
}child::child()

cout << "child default construction" << endl;
}
child::child(char *str1, char *str2) : parents( str1 )
{
cout << "child construction" << endl;
strcpy(string2,str2);
}
void child::display()
{
cout << this->string1 << endl;
cout << this->string2 << endl;
}child::~child()
{
}void main()
{
parents::pHead=NULL;
parents  test("test string");
test.display();
child children("old", "young");
children.display();
parents::pHead->display();// 下面这条语句出现内存不能读的问题
((child *)test.pNext)->display();
}

解决方案 »

  1.   

    this->pNext=NULL;
    //这句话导致test.pNext为空,函数调用失败
      

  2.   

    因为链表最后是以NULL结束的,我的意思是在执行构造函数过程中,把当前的对象加入链表,并在最后补上 NULL,并没有错啊.test是头, test的下一个是children ,不是NULL
      

  3.   

    改成这样:
    child *pS;
    pS=(child *)pHead;
    while ( pS!= NULL && pS->pNext != NULL)
    {
        pS=(child*)pS->pNext;
    }
    if(pS != NULL)
    {
        pS->pNext = (child*)this;
    }
      

  4.   

    改成这样:
    child *pS;
    pS=(child *)pHead;
    while ( pS!= NULL && pS->pNext != NULL)
    {
        pS=(child*)pS->pNext;
    }
    if(pS != NULL)
    {
        pS->pNext = (child*)this;
    }