创建对象数组会导致问题

Creating an array of objects causes an issue

本文关键字:问题 数组 创建对象      更新时间:2023-10-16

>我创建以下两个对象:

bool    Reception::createNProcess()
{
  for (int y = 0; y < 3; ++y)
    {
      Process           *pro = new Process; // forks() at construction
      Thread            *t = new Thread[5];
      this->addProcess(pro); // Adds the new process to a vector
      if (pro->getPid() == 0)
      {
         for (int i = 0; i < 5; ++i)
         {
           pro->addThread(&t[i]); // Adds the new thread to a vector
           t[i].startThread();
         }
      }
}

我在其中创建了 3 个进程(我已经封装在 Process 中),并在每个进程中创建了 5 个线程。

但我不确定以下行是否正确:

Thread            *t = new Thread[5];

因为我的两个函数addProcessaddThread都分别采用指向ProcessThread的指针,但编译器要求引用t[i]以进行addThread,我不明白为什么。

void    Process::addThread(Thread *t)
{
  this->threads_.push_back(t);
}
void    Reception::addProcess(Process *p)
{
  this->createdPro.push_back(p);
}

createdProReception 类中定义如下:

 std::vector<Process *>        createdPro;

threads_Process类中是这样的:

 std::vector<Thread *>         threads_;

错误消息(显而易见)如下:

错误:调用"进程::添加线程(线程&)"没有匹配函数 pro->addThread(t[i]);

进程.hpp:29:10: 注意: 候选者: 无效 进程::添加线程(线程*) void addThread(Thread *);

process.hpp:29:10:注意:参数 1 没有从"线程"到"线程*"的已知转换

即使我将Thread定义为指针。

您已定义成员函数以采用指针:

void Process::addThread(Thread *t)
{
    ...
}

然后,您为 &t[i] 调用此函数,这是一个指针,应该可以完美地工作:

      pro->addThread(&t[i]); // Adds the new thread to a vector

您也可以使用 t+i 调用它,它仍然可以。但是,您的错误消息告诉我们一些不同的东西:编译器找不到pro->addThread(t[i]);的匹配项(即缺少&)。

要么你在问题中打错了字

,要么你在代码中打错了字。 或者你在忘记了 & 符号的地方有另一个调用:t[i]当然会指定一个对象(它相当于 *(t+i) )而不是指针,并导致您拥有的错误消息(演示 mcve)