简体   繁体   English

如果我声明一个指针,则该类的指针成员会怎样?

[英]What happen with the pointer members of a class if I declare a pointer?

I have written the following code: 我写了以下代码:

#include <iostream>

using namespace std;

class Node {
public:
    int id;
    Node* n;
};

int main()
{
    Node* node;
    cout << node->n;
    return 0;
}

In this case I declared a pointer (it's uninitializated) but in the output I obtain an address given by "n". 在这种情况下,我声明了一个指针(未初始化),但是在输出中,我获得了由“ n”给出的地址。 if I don't initializate the pointer, why does the code show me a reference?. 如果我不初始化指针,为什么代码会向我显示引用?

It is a wild pointer. 这是一个野指针。 VC compilers assign to those pointers the value 0xcdcdcdcd which may point to the last memory in the RAM ( not sure of that) . VC编译器为这些指针分配了值0xcdcdcdcd ,该值可能指向RAM的最后一个内存(不确定)。 You should not dereference this kind of pointers because the compiler will throw a violation memory access.If you doesn't want to assign a object of type Node to the pointer it is strongly recommended that you assign the pointer with NULL value.In this case you will always be able to check in the code if the pointer points to a real object or is not assigned by checking his address. 您不应该取消引用此类指针,因为编译器将抛出违规内存访问。如果您不想将Node类型的对象分配给指针,强烈建议您为指针分配NULL您将始终能够在代码中签入指针是否指向真实对象或是否通过检查其地址而未分配。

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

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