关于类内的结构体的构造函数
上一个贴结早了......
- C/C++ code
#include<iostream>using namespace std;class Linked{ protected: struct Node{ int item; Node *next; Node():next(NULL),item(0){} //此处添加了构造函数 }; Node* head; long length; public: Linked(){ length=0; } void insert(int i){ if((head->next)==NULL){ Node* newItem; newItem->item=i; head->next=newItem; length++; cout<<this->length; } } };int main(){ Linked itr; itr.insert(2); system("pause"); return 0;}
之前代码中的Node* head没有被初始化,结果出现下面的错误
- C/C++ code
Unhandled exception at 0x004114c8 in test.exe: 0xC0000005: Access violation reading location 0xccccccd0.First-chance exception at 0x004114c8 in test.exe: 0xC0000005: Access violation reading location 0xccccccd0.
添加构造函数后为什么还是这个错?
[解决办法]
楼主你构造函数里面lenth=0,那么head这个指针为什么呢?第一次插入数据的时候你居然调用head指针了。这才是你的问题所在啊