C++ 中声明一个变量,这个变量具有一定的作用域和生命周期。
作用域: 就是一个变量被引用的范围。
生命周期:这个变量可以被引用的时间段,不同生命周期的变量,在程序内存中的分布位置不同,一个程序内存分为:代码区、全局数据区、堆区、栈区,不同的内存区域对应不同的生命周期;
如果没有当前函数以外的指针指向它,则在当前函数结束时,会将当前变量析构;如果有函数以外的指针指向它,则不会被析构;
如果用New 的方式声明变量,则当前空间会被保存至程序运行结束;
#includeusing namespace std; struct Node{ int value =1; Node *next; }n1; int main(){ Node *s = &n1; cout< value<
#includeusing namespace std; struct Node{ int value =1; Node *next; }n1; int main(){ Node *s = new Node; cout< value<
new 相当于重新定义了一个结果体对象,并把地址传给 s;
#includeusing namespace std; struct Node{ int value ; Node *next; }n1,n2,*start; int main(){ n1.value = 1; n2.value = 2; start = &n1; n1.next = &n2; for(int i=0;i<2;i++){ cout< value< next; } return 0; }
#includeusing namespace std; struct Node{ int value ; Node *next; }*start; int main(){ Node *n1 = new Node; Node *n2 = new Node; n1->value = 1; n2->value = 2; n1->next = n2; start = n1; for(int i=0;i<2;i++){ cout< value< next; } return 0; }