将指针变量设置为多个值
Setting a pointer variable to multiple values
我正在编写使用自定义链表的代码 class。列表 class 具有以下功能:
void linkedList::expire(Interval *interval, int64 currentDt)
{
node *t = head, *d;
while ( t != NULL )
{
if ( t->addedDt < currentDt - ( interval->time + (((long long int)interval->month)*30*24*3600*1000000) ) )
{
// this node is older than the expiration and must be deleted
d = t;
t = t->next;
if ( head == d )
head = t;
if ( current == d )
current = t;
if ( tail == d )
tail = NULL;
nodes--;
//printf("Expired %d: %s\n", d->key, d->value);
delete d;
}
else
{
t = t->next;
}
}
}
我不明白的是函数中的第一行代码:
node *t = head, *d;
这段代码如何编译?如何将两个值分配给一个变量,或者这是一些 shorthand 的快捷方式? head 是 *node 类型的成员变量,但在其他任何地方都找不到 d。
这是两个定义,不是 comma operator1。它们相当于
node* t = head;
node* d;
1 逗号运算符在 C++ 中所有运算符的优先级最低,因此调用它需要括号:
node* t = (head, *d);
如果 d
是 node**
类型,这将正常工作。
通常在 c++ 中,您可以列出多个定义,并用逗号分隔它们:
int a,b,c,d;
将定义 4 个整数。危险在于指针的处理方式可能很明显:
int* a,b,c,d;
将把a声明为一个指向int的指针,剩下的就是int。因此,在样式中声明指针的做法并不罕见:
int *a, *b;
其中声明了两个整数指针。
我正在编写使用自定义链表的代码 class。列表 class 具有以下功能:
void linkedList::expire(Interval *interval, int64 currentDt)
{
node *t = head, *d;
while ( t != NULL )
{
if ( t->addedDt < currentDt - ( interval->time + (((long long int)interval->month)*30*24*3600*1000000) ) )
{
// this node is older than the expiration and must be deleted
d = t;
t = t->next;
if ( head == d )
head = t;
if ( current == d )
current = t;
if ( tail == d )
tail = NULL;
nodes--;
//printf("Expired %d: %s\n", d->key, d->value);
delete d;
}
else
{
t = t->next;
}
}
}
我不明白的是函数中的第一行代码:
node *t = head, *d;
这段代码如何编译?如何将两个值分配给一个变量,或者这是一些 shorthand 的快捷方式? head 是 *node 类型的成员变量,但在其他任何地方都找不到 d。
这是两个定义,不是 comma operator1。它们相当于
node* t = head;
node* d;
1 逗号运算符在 C++ 中所有运算符的优先级最低,因此调用它需要括号:
node* t = (head, *d);
如果 d
是 node**
类型,这将正常工作。
通常在 c++ 中,您可以列出多个定义,并用逗号分隔它们:
int a,b,c,d;
将定义 4 个整数。危险在于指针的处理方式可能很明显:
int* a,b,c,d;
将把a声明为一个指向int的指针,剩下的就是int。因此,在样式中声明指针的做法并不罕见:
int *a, *b;
其中声明了两个整数指针。