创建对象数组会导致问题
Creating an array of objects causes an issue
>我创建以下两个对象:
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];
因为我的两个函数addProcess
和addThread
都分别采用指向Process
和Thread
的指针,但编译器要求引用t[i]
以进行addThread
,我不明白为什么。
void Process::addThread(Thread *t)
{
this->threads_.push_back(t);
}
void Reception::addProcess(Process *p)
{
this->createdPro.push_back(p);
}
createdPro
在 Reception
类中定义如下:
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)
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 输入std::数组时出现问题
- 类对象数组的问题会导致崩溃
- 传递二维数组时出现问题
- 从 C++ 中的函数返回数组地址问题
- 使用数组时出现问题
- 打印问题.我在数组中打印值时遇到一些问题
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 将字节数组转换为带有字节序问题的指针
- C++ 填充数组时遇到问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 当我尝试通过 arduino 上的引用传递布尔数组时出现问题
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 编写 cin.get() 以接收字符数组时出现问题
- 在 C++ Consol 中的数组中执行用户命令时出现问题
- 存储另一个函数返回的布尔数组时遇到问题
- 当我在 CLion 中读取数组中的 txt 文件时C++编码问题
- 运行时C++数组初始化问题
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组