【问题标题】:Pointer to a Struct/ Class within the struct/class C++指向结构/类 C++ 中的结构/类的指针
【发布时间】:2021-04-01 14:15:54
【问题描述】:

您好,我来自 Java 背景,对 C++ 很陌生 在我的中级 Java 编程中,我从未遇到过声明某个对象的情况 该类主体中的类,现在正在研究 C++ 中的链表,这里是这段代码和几个 我遇到的其他地方指向该类/结构的指针在其主体中声明,即 Struct ListNode * next;在下面的代码中

private:
// Declare a structure for the list
structListNode{
float value;
structListNode*next;
};
ListNode*head; // List head pointer
public:
FloatList(void) { // Constructor
head = NULL;
}
~FloatList(void) { }; // Destructor
void appendNode(float);
void displayList(void);
void deleteNode(float);
};

或节点*下一个;在下面的这段代码中

class Node {

    int data; // The value stored in node
    Node* next; // The address of next node
    }

我真的无法理解它的含义或进展如何,有人可以向我解释一下吗?

【问题讨论】:

  • 您应该了解指针是什么以及它们是如何工作的。代码没有声明“该类主体内某个类的对象”。它声明了一个指向该类主体内某个类的对象的指针,这是不同的。 good book 可能会有所帮助。 (想象一下,指针基本上是一个地址。为什么将地址存储在类实例中会有任何问题?)
  • 在 Java 中这相当于:class Node { int data; Node next;}。这意味着next 在 c++ 中引用(在 java 中)和指向(通过指针)到 Node 的实例
  • 你了解链表的概念吗?你见过无数优秀的可视化吗?带有指向另一个 Node 的指针的 Node 是该数据结构的标志。
  • 我确实知道它不是类/结构体中的对象,但是当我在类体中创建类的指针时,内存中的情况如何?它是如何工作的?
  • @AliM “它是如何工作的?” — 这在很大程度上取决于您分配给该指针的内容。在你的情况下,只需谷歌“C++ 链表”。

标签: c++ class object pointers


【解决方案1】:

结构/类内部的指针不是该结构/类的“对象”,而是相同类型对象的指针。它只是存储/保存在其他地方创建的对象的地址,因此它可以访问或修改它们而无需复制它们的内容。

举个例子;

class Node {
  int data;
  Node* next;
};

int main(){
  Node* head = NULL; // This is a pointer, not an object.
                     // It points to NULL (i.e. nothing) yet.

  Node n1, n2; // These two are "objects" of Node class

  head = &n1; // head now points to n1, i.e. holds memory address of n1
  n1.data = 10; // n1.data contains 10
  n1.next = &n2; // n1.next points to the object n2

  n2.data = 20; // n2.data contains 20
  n2.next = NULL; // n2.next points to nothing

  head->data = 5; // now, n1.data contains 5, instead of 10
  head->next->data = 15; // now, n2.data contains 15, instead of 20

  return 0;
}

【讨论】:

  • @AliM 最好的感谢是接受答案。
猜你喜欢
  • 2021-01-12
  • 2022-06-15
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
相关资源
最近更新 更多