github_34713651 2016-04-19 03:43 采纳率: 100%
浏览 1184
已采纳

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是允许的,求教大神。

  • 写回答

1条回答

  • lbcab 2016-04-19 04:19
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型