简体   繁体   English

关于节点指针分配的困惑

[英]Confusion about node pointer assignment

My code looks like this:我的代码如下所示:

#include <iostream>

struct Node {
   double data;
   Node* next;
};

int main(){
   Node* a;
   a = new Node;
}

I am having a hard time understanding why the assignment would work for a pointer.我很难理解为什么该作业适用于指针。 Because a is type Node* but the new node is type Node .因为a是类型Node*但新节点是类型Node

At the beginning of my class, I was taught that pointer assignment needs to always be an address.在我的 class 开始时,我被告知指针分配必须始终是地址。

For example:例如:

int * x;
int y = 5;

This would be allowed:这将是允许的:

x = &5;

But this wouldn't:但这不会:

x = y;

So, by that same logic, shouldn't the assignment of Node* a;所以,按照同样的逻辑,不应该分配Node* a; be:是:

a = &(new Node);

Instead of:代替:

a = new Node;

? ?

When you call new , it creates a new object and returns a pointer to that object.当您调用new时,它会创建一个新的 object 并返回指向该 object 的指针。 It is quite common to store that pointer in a pointer variable.将该指针存储在指针变量中是很常见的。 You would use & new(...) if it returned a reference to the newly-created object.如果它返回对新创建的 object 的引用,您将使用& new(...) But it doesn't.但事实并非如此。

but the new Node is type Node.但新节点是类型节点。

is absolutely wrong.是绝对错误的。 This is not Java.这不是 Java。 new Node returns a pointer to a freshly allocated on heap Node. new Node返回一个指向堆上新分配的 Node 的指针。

First of all, every assignment requires correct type .首先,每个作业都需要正确的 type Either you provide left argument of the exact same type as the variable you assign to, or of a type you can convert from.您可以提供与您分配给的变量完全相同类型的左参数,或者您可以从中转换的类型。 Eg例如

int x = 5; //here x is a type of int and 5 is also an int

or或者

double w = 3; //here w is a type of double and 3 is again int but int can be converted to double

in contrary相对的

int z = 3.2; //won't compile because 3.2 is a float and floats have to be explicitly casted to ints.

Now, with your code, Node* is a type you read as Node pointer and new allocates memory on heap, creates new object and return its address which in this case is also Node pointer .现在,使用您的代码, Node*是您读取为Node pointer的类型,并且new在堆上分配 memory ,创建新的 object 并返回其地址,在这种情况下也是Node pointer Types match and everything works.类型匹配,一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM