【问题标题】:Error: expression must have pointer-to-class type错误:表达式必须具有指向类的类型
【发布时间】:2020-03-15 19:25:35
【问题描述】:

我正在尝试使用结构来实现队列。这是一个结构本身:

struct Item
{
    datatype data;
    Item* next;
};

但是,当我尝试添加新元素时,出现错误:

void enqueue(Item** front, Item** rear, datatype D) { //add element to queue
    Item* temp;
    temp = new Item;
    temp->data = D;
    temp->next = NULL;
    if (*front == NULL){ // if queue is empty, make temp the first element
        *front = temp;
    }
    else { // else add it to the end
        rear->next = temp; //error is here
        *rear = temp;
    }
}

我尝试过类似(*rear)->next = temp; 的操作,但接下来会保持 NULL。

您能帮忙解决这个问题吗?谢谢。

【问题讨论】:

    标签: c++ pointers queue


    【解决方案1】:

    如果队列为空,则只分配front,但rear 也必须指向同一个Item

    if (*front == nullptr){ // if queue is empty, make temp the first element
        *front = temp;
    }
    else { // else add it to the end
        (*rear)->next = temp;         // <- fix like this
    }
    *rear = temp;                     // <- do this in both cases
    

    否则你enqueue 的下一个对象将使用rear,它指向你在开始时初始化它的对象,可能是NULL

    【讨论】:

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