c++ - C++中的结构指针

标签 c++

为了完成我的作业,我不得不用 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;

虽然可以使用函数,但我有一些问题:

  1. 为什么指针示例中的返回值是结构而不是指针?
  2. 为什么元素现在有双倍索引,它们之间的元素是什么?
  3. 为什么没有段错误?

如果有人向我解释这些时刻或给我可以学习的资源,我将非常感激

最佳答案

那是因为 v4[0] (和其他人)实际上并没有调用你的 Node::operator[] .那是因为v4不是 Node , 这是一个 Node* , 指针在 operator[] 后面有一个内在的含义: v4[i] == *(v4 + i) (也就是说,我们只是索引到那个“数组”)。所以当你写类似 v4[3] 的东西时,那不是调用 operator[](3) ...它反而给你一个 NodeNodev4 之后在某个地方的内存中,这基本上只是垃圾。

为了得到你想要发生的事情,你必须先取消引用指针:

(*v4)[0]
(*v6)[1]
// etc

关于c++ - C++中的结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35774253/

相关文章:

c++ - 在 qt c++ 中使用 paintevent 的循环中 sleep

C++ 在 << 作为参数后使用 stringstream

c++ - ArrayList 无法返回结构

c++ - 使用 range-v3 读取逗号分隔的数字列表

c++ - 以三个无符号字符为键的 Unordered_map

c++ - 声明两个使用相同参数的不同方法

c++ - 如果我不 odr-use 一个变量,我可以在翻译单元中对它有多个定义吗?

c# - 从 C# 中的非托管 C++ DLL 获取字节数组上的指针

android - 如何使用 cmake 和 Android NDK 在 C++ 中加载线程支持

c++ - 如何使用 boost.python 导出复杂类