C++操作符【】重载BUG

小白一只,最近在学C++重载符时,想到能不能写一个链表类,重载[]来模拟数组,但遇到了BUG
代码如下:

List.h:
#include
using namespace std;

struct List
{
int data; //数据;
struct List * pNext; //指向下一节点
};

class L
{
public:
L();
int operator const;
~L();

private:
int count; //数据个数;
struct List * Phead; //链表头指针;
};

List.cpp:
#include "A.h"
#include
using namespace std;
L::L() //创建链表;
{
struct List * Phead,* p1,* p2;
Phead = new struct List;
p1 = p2 = Phead;
cout<<"请输入数据个数"< cin>>count;
for (int i = 1; i <= count ; ++i) //创建链表节点来储存数据;
{
p1 = new struct List;
cout<<"请输入第"< cin>>p1->data;
p2->pNext = p1;
p2 = p1;
}
p1 ->pNext = NULL;
}

int L::operator const
{
if (n+1>count) //检查越界;
{
cout<<"数组越界"< exit(0);
}
struct List * p = Phead->pNext;
for (int i = 0;i < n; ++i) //找出第n个节点;
{
p = p->pNext; //BUG!!!!
}
return p->data; //返回数据;
}

L::~L() //销毁链表;
{
...
}

main:
#include
#include
#include "List.h"
using namespace std;

int main(void)
{
L l1;
cout<<l1[0]<<endl;
system("pause");
return 0;
}

调试的时候第一次到BUG那行就报错,但我找不出来错误,因为在别的函数中p=p->pNext是允许的,求教大神。

你在init()函数中定义了变量struct List * Phead, 覆盖了成员变量, 所以你在init中的赋值并没有更新Phead指针的值.
将init中的变量Phead删除, 再试一下.