将指针变量设置为多个值

Setting a pointer variable to multiple values

本文关键字:设置 指针 变量      更新时间:2023-10-16

我正在编写使用自定义链表类的代码。list类具有以下功能:

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: %sn", d->key, d->value);
             delete d;
         }
         else
         {
            t = t->next;
         }
     }
}

我不明白的是函数中的第一行代码:

node *t = head, *d;

这段代码是如何编译的?如何将两个值赋给一个变量,或者这是某种简写的快捷方式?Head是*node类型的成员变量,但是d在其他任何地方都找不到。

这是两个定义,不是逗号操作符1。它们相当于

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 *a, *b; 

声明了两个整型指针