简体   繁体   English

为什么我们不能在不使用指针的情况下初始化节点?

[英]why cannot we initialize a node without using a pointer?

I have recently started learning data structure and as a beginner, I have a query while implementing linked list nodes, why do we have to initialize node using a pointer only?我最近开始学习数据结构,作为初学者,我在实现链表节点时有一个疑问,为什么我们必须只使用指针来初始化节点?

class node{
    public:
    int data;
    node* next;
    node(int val){
        data = val;
        next = NULL;
    }
 };
 int main(){
    node* head = NULL;
    node head = NULL; // this throws an error which i cannot understand
 }

Actually you can initialize the node by value.实际上你可以按值初始化节点。 If you want to initialize a node with value, according to your constructor node(int val) , you have to code like below:如果你想用值初始化一个节点,根据你的构造函数node(int val) ,你必须像下面这样编码:

class node{
    public:
    int data;
    node* next;
    explicit node(int val){
        data = val;
        next = NULL;
    }
 };
 int main(){
    int value = 777;
    //node* head = NULL; // Initialize head pointers to null
    node head(value);   // By your constructor definition
 }

EDIT: By the way, marking a constructor as explicit is a very good habit to have, as it prevents unexpected conversion, as Duthomhas commented.编辑:顺便说一句,将构造函数标记为显式是一个非常好的习惯,因为它可以防止意外转换,正如 Duthomhas 评论的那样。

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

相关问题 为什么我们使用指向一个的指针和指向另一个的普通指针? - Why are we using pointer to pointer for one and a normal pointer to another? 为什么我们不能在 C++ 中初始化类的成员变量 - Why we cannot initialize the member variable of a class in C++ 无法使用std :: unique_ptr初始化指针 - Cannot initialize a pointer using std::unique_ptr 在QMap中插入QObject *-无法初始化或传递指针 - Inserting QObject * in QMap - cannot initialize or pass the pointer 无法使用base clase rvalue初始化指向子类的指针 - Cannot initialize pointer to a subclass with base clase rvalue 为什么我们要返回指向节点的指针而不是 void function 来实现 avl 树? - Why do we return a pointer to a node instead of void function for avl tree implementation? 我们可以通过初始化列表中的智能指针来初始化结构成员吗? - Can we initialize structure memebers through smart pointer in initialization list? 为什么没有基类指针或引用我们就不能在C ++中实现多态? - Why we can't implement polymorphism in C++ without base class pointer or reference? 为什么以及何时必须在C ++中使用之前初始化字符串? - Why and when do we have to initialize a string before using in C++? 无法将“ this”指针从“ const Node”转换为“ Node&” - Cannot convert 'this' pointer from 'const Node' to 'Node &'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM