【问题标题】:"no matching function for call" when trying to cin.read into a 2d array尝试 cin.read 进入二维数组时出现“没有匹配的调用函数”
【发布时间】:2016-02-19 21:28:02
【问题描述】:

像素是一个包含 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&lt;char&gt;::read(PpmImage::Pixel&amp;, unsigned int)'

这是什么意思???

【问题讨论】:

  • 与使用数组无关,与尝试传递用户定义的类型(Pixel)有关。 read 可能不适合您。 cplusplus.com/reference/istream/istream/read
  • 它应该是&amp;PMatrix[i][0] 或只是PMatrix[i] 加上一些reinterpret_cast&lt;char*&gt;。但我猜它在运行时仍然会失败(因为对齐?)

标签: c++ arrays io cin


【解决方案1】:

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

通常,会为他们的班级重载operator&gt;&gt;istream

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 类型,您可以将其强制转换为指向第一个元素的指针。这将读取三个chars 并将它们存储到PMatrix[i][0]。不过,我建议使用第一种方法。它更惯用,看起来不太不稳定。

【讨论】:

  • 但是我将如何添加数组指向的其他像素?为什么我不能 cin.read(reinterpret_cast&lt;char*&gt;(PMatrix[i]), 5*3); 一次读取 5 个像素?
  • @user 使用嵌套循环遍历该数组。该结构可以在 rgb 之后具有打包字节。当只有 3 个字节是数据时,您的 Pixel 可能有 4 个字节长。
猜你喜欢
  • 2021-12-27
  • 2013-09-12
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 2019-01-26
相关资源
最近更新 更多