模板和 for 循环出现问题

Trouble with templates and for loops

本文关键字:问题 循环 for      更新时间:2023-10-16

我有这段代码,它给了我一个指示两个问题的单一错误。

int healthyConst = 0;
int sickConst = 1;
int recoveredConst = 2;
GraphMatrix<int, double> graph (100);
for (int i = 0; i < sampleSize; i++)
{
if(std::rand() % 2 > 0.05) graph.setVertexInfo(i, sickConst); //Error
else graph.setVertexInfo(i, healthyConst); 
}

错误是:

error: 调用 GraphMatrix::setVertexInfo(int&, int*) 时没有匹配函数

有问题的函数在源代码中声明如下:

void GraphMatrix::setVertexInfo(int v, VertexObject& info)

首先,我不应该成为参考。这对我来说似乎是荒谬的,但我无法解决这个问题。如果我试图智胜编译器并键入for(int* i = 0...)错误现在抱怨setVertexInfo(int&*, int*),我什至不明白这意味着什么。

其次,病康斯特不是一个指针。它只是一个整数。现在我意识到该方法,如所写,接受VertexObject&,而不是VertexObject,但也*sickConst导致编译器抱怨invalid type argument of 'unary *'。我也尝试了&sickConst,编译器并不意外地将其解释为指针。

另请注意,对于 for 循环的第二行,可能出于相同的原因抛出相同的错误。

问题是:为什么我会收到这些错误,我该如何修复它们?

您声明源代码中的函数声明如下:

void GraphMatrix::setVertexInfo(int v, VertexObject& info)

但是,在您的 for 循环中,您正在传递一种int。要么更改函数声明和定义以接受某种类型的int,要么更改作为VertexObject传递给函数的类型。