[英]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.