为了完成作业,我必须在C++中实现一个列表,因此我定义了一个结构:
struct Node {
int value;
Node * next;
Node * operator [] (int index)//to get the indexed node like in an array
{
Node *current = this;
for (int i = 0; i<index; i++)
{
if (current==NULL) return NULL;
current = current->next;
}
return current;
}
};当我将它与实际结构一起使用时,它工作得很好:
Node v1, v2, v3;
v1.next = &v2;
v2.next = &v3;
v3.value = 4;
v3.next = NULL;
cout<<v1[2]->value<<endl;//4
cout<<v2[1]->value<<endl;//4
cout<<v3[0]->value<<endl;//4; works just as planned
cout<<v3[1]->value<<endl;//Segmentation fault但是当我尝试用指针的时候,事情就变得一团糟了:
Node *v4, *v5, *v6;
v4 = new Node;
v5 = new Node;
v6 = new Node;
v4->next = v5;
v4->value = 44;
v5->next = v6;
v5->value = 45;
v6->next = NULL;
v6->value = 4646;
//cout cout<<v4[0]->value<<endl; compiler says it's not a pointer
cout<<v4[0].value<<endl;//44
cout<<v4[1].value<<endl;//1851014134
cout<<v4[2].value<<endl;//45
cout<<v4[3].value<<endl;//1851014134
cout<<v4[4].value<<endl;//4646
cout<<v4[5].value<<endl;//1985297391;no segmentation fault
cout<<v6[1].value<<endl;//1985297391;no segmentation fault even though the next was NULL
delete v4;
delete v5;
delete v6;虽然可以使用函数,但我有一些问题:
如果有人解释了这些时刻,或者给了我我可以从中学到的信息,我会非常感激
发布于 2016-03-03 14:15:24
通过这样做
v4 = new Node;
cout<<v4[0].value<<endl;//44
cout<<v4[1].value<<endl;//1851014134
cout<<v4[2].value<<endl;//45
cout<<v4[3].value<<endl;//1851014134
cout<<v4[4].value<<endl;//4646
cout<<v4[5].value<<endl;//1985297391;no segmentation fault您不是在调用struct的operator[],而是在进行指针取消引用,v4[1]等于++v4; *v4;,因此此代码将导致无法预测的行为,因为您正在取消引用一些垃圾。要使它按您的需要工作,您需要将其更改为:
cout<<v4->operator[](0).value<<endl;
cout<<v4->operator[](1).value<<endl;
cout<<v4->operator[](2).value<<endl;
...https://stackoverflow.com/questions/35774253
复制相似问题