【问题标题】:Setting a pointer variable to multiple values将指针变量设置为多个值
【发布时间】:2015-10-21 13:05:45
【问题描述】:

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

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;

这段代码是如何编译的?如何将两个值分配给单个变量,或者这是一些速记快捷方式? head 是 *node 类型的成员变量,但在其他任何地方都找不到 d。

【问题讨论】:

    标签: c++ pointers variable-assignment


    【解决方案1】:

    这是两个定义,不是comma operator1。它们相当于

    node* t = head;
    node* d;
    

    1 逗号运算符在 C++ 中的所有运算符中的优先级最低,因此调用它需要括号:

    node* t = (head, *d);
    

    如果dnode** 类型,这将正常工作。

    【讨论】:

      【解决方案2】:

      通常在 c++ 中,您可以列出多个定义,用逗号分隔它们:

      int a,b,c,d;
      

      将定义 4 个整数。危险在于指针的处理方式可能很明显:

      int* a,b,c,d;
      

      将声明 a 为指向 int 的指针,其余的将只是 int。因此,在样式中声明指针并不罕见:

      int *a, *b; 
      

      它声明了两个整数指针。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-25
        • 1970-01-01
        相关资源
        最近更新 更多