简体   繁体   English

如何在C ++中的成员函数内部访问对象数组?

[英]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. 我正在编写面向对象的FCFS调度算法版本,但遇到了问题。 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. 我尝试使用“ this-pointer”,但是由于当前进程的完成时间的计算需要上一个的完成时间,因此“ this”将不起作用。 Or at least I think it won't. 或者至少我认为不会。 I have no idea how to access "previous" object using "this" 我不知道如何使用“ this”访问“ previous”对象

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. 由于我使用process [pid]来调用scheduleProcess(),process [pid]是对象的向量,因此我应该能够处理与process [pid]对象有关的变量。 How do I access process[pid-1] in the function itself? 我如何在函数本身中访问process [pid-1]? (Without passing process vector as an argument) (不传递过程向量作为参数)

Since scheduleProcess is a member of Process , it only knows what the Process object knows. 由于scheduleProcessProcess的成员,因此它仅知道Process对象知道的内容。 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 . 一种避免所有情况的可移植解决方案,就是简单地将上一个过程的完成时间作为参数传递,因为您知道在调用scheduleProcess该值。 Where there is not a previous process (the first entry in the array), this finish time would be 0. 如果没有上一个进程(数组中的第一个条目),则此完成时间将为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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