【发布时间】:2018-02-03 23:22:39
【问题描述】:
我在尝试为我的结构 PCB 的成员变量赋值时遇到问题。我正在使用指向我的结构的指针队列。所以我首先取消引用传递给inititiate_process 函数的指针,然后尝试从ready_queue 引用指针来访问成员变量。如何访问此成员变量?我在这行代码(static_cast<PCB*>(ready_queue->front()))->next_pcb_ptr = &pcb; 上得到一个“无效的类型转换”。
这是我在头文件中的结构
#ifndef PCB_H
#define PCB_H
struct PCB {
int p_id;
int *page_table_ptr;
int page_table_size;
int *next_pcb_ptr;
};
#endif // !PCB_H
这是我的源 cpp 文件
#include <iostream>
#include <queue>
#include "PCB.h"
using namespace std;
void initiate_process(queue<int*>* ready_queue) {
// allocate dynamic memory for the PCB
PCB* pcb = new PCB;
// assign pcb next
if(!(ready_queue->empty())){
// get prior pcb and set its next pointer to current
(static_cast<PCB*>(ready_queue->front()))->next_pcb_ptr = &pcb;
}
}
void main(){
queue<int *> ready_queue;
initiate_process(&ready_queue);
}
【问题讨论】:
-
考虑使用
std::unique_ptr<T>而不是T* -
通过传递引用而不是指针来为自己省点麻烦。
void initiate_process(queue<int*>* ready_queue)->void initiate_process(queue<int*>& ready_queue) -
为什么不在队列中存储指向
PCBs 的指针?您似乎正在竭尽全力让自己变得困难。 -
不管怎样,不管你一开始做了什么转换,
next_pcb_ptr仍然是int *而&pcb是PCB**。我认为解决这个问题的方法是停下来重新思考你在做什么。 -
请不要编辑问题以显示正确的解决方案,因为如果您这样做,答案将不再有意义。我已经备份了你的一些编辑。如果您觉得需要在问题中添加 cmets 或更新,请至少将它们放在旧文本之后。