简体   繁体   中英

How to access array of objects inside member function in C++?

I'm writing an Object Oriented version of FCFS scheduling algorithm, and I've hit a problem. I need to know if there's any way to access an array of objects inside the member function definition, without passing it as a parameter explicitly.

I've tried using "this-pointer", but since the calculation of finish time of current process requires the finish time of the previous, "this" won't work. Or at least I think it won't. I have no idea how to access "previous" object using "this"

void Process :: scheduleProcess(int pid) {
     if(pid == 0) finishTime = burstTime;
     else finishTime = burstTime + 
     this->[pid-1].finishTime;

     turnAroundTime = finishTime - arrivalTime;
     waitingTime = turnAroundTime - burstTime;
}

I can obviously send the array of objects as a parameter and use it directly. I just want to know if there's a better way to do this:

This is the part that's calling the aforementioned function:

 for(int clockTime = 0; clockTime <= maxArrivalTime(process); 
 clockTime++) {
    // If clockTime occurs in arrivalTime, return pid of that 
 process
         int pid = arrivalTimeOf(clockTime, process);
         if(pid >= 0) {            
             process[pid].scheduleProcess(pid);

         } else continue;
 }

Since I'm calling scheduleProcess() using process[pid], which is a vector of objects, I should be able to manipulate the variables pertaining to process[pid] object. How do I access process[pid-1] in the function itself? (Without passing process vector as an argument)

Since scheduleProcess is a member of Process , it only knows what the Process object knows. The previous process is unknown at this level. There are ways that use Undefined Behavior and make more assumptions about your code to get around this, but these should be avoided.

One portable solution to avoid all that is to simply pass in the previous process's finish time as a parameter, since you know this value at the point of the call to scheduleProcess . Where there is not a previous process (the first entry in the array), this finish time would be 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM