尝试读取 2D 数组时"no matching function for call"

"no matching function for call" when trying to cin.read into a 2d array

本文关键字:no matching for call function 读取 2D 数组      更新时间:2023-10-16

Pixel 是一个包含 3 个字符的结构。 struct Pixel { char r, g, b} ;

int H = 5, C = 10;
Pixel *PMatrix[H]; // Creates an array of pointers to pixels
for (int h = 0 ; r < H ; h++) {
    PMatrix[r] = new Pixel[C]; //Each row points to an array of pixels
}

我有一个 PPM 文件,我正在尝试逐行将字节读取到图像表示的像素矩阵中。

for (unsigned int i = 0; i < height; i++){
    cin.read(PMatrix[i][0], width*3);
}

我也尝试过循环中的"cin.read(PMatrix[i], width*3);"

我收到错误no matching function for call to 'std::basic_istream<char>::read(PpmImage::Pixel&, unsigned int)'

这是什么意思???

错误在于您创建了一个类,并且您正在将其传递给没有重载的标准库函数。 PMatrix是一个Pixel*[],所以使用[]一次得到一个Pixel*,然后再次给出一个Pixelcin.readPixel一无所知,也没有操作员来处理它。

通常,一个人会为他们的班级和istream超载operator>>

std::istream& operator>>(std::istream& lhs, Pixel& rhs)
{
    lhs >> rhs.r >> rhs.g >> rhs.b;
    return lhs;
}
//...
cin >> PMatrix[i][0]; //calls our overloaded operator

我不确定,但我想你可能一直在尝试这样做:

cin.read(reinterpret_cast<char*>(PMatrix[i]), 3); //ew magic number

由于Pixel是 POD 类型,因此您可以将其强制转换为指向第一个元素的指针。这将读取三个char并将它们存储到PMatrix[i][0]中。不过,我建议使用第一种方法。它更惯用,看起来不那么不稳定。

相关文章: