错误 C2665:'cv::fillPoly':2 个重载都无法转换所有参数类型

error C2665: 'cv::fillPoly' : none of the 2 overloads could convert all the argument types

本文关键字:转换 参数 类型 cv C2665 fillPoly 重载 错误      更新时间:2023-10-16

我收到这个奇怪的错误,这段代码编译(并正确显示三角形):

Point pts[3] = { Point(20, 20), Point(60, 20), Point(40, 40) };
const Point *ptsp = pts;
int npts[1] = {3};  
fillPoly(img, &ptsp, npts, 1, Scalar(255, 255, 0));

但是如果我用 Point *ptsp = pts 替换const Point *ptsp = pts;,那么我会收到此错误:

1>C:WorkspaceImageProcessingTutorialssrcmain.cpp(16): error C2665: 'cv::fillPoly' : none of the 2 overloads could convert all the argument types
1>          C:WorkspaceImageProcessingopencvbuildincludeopencv2/core/core.hpp(2632): could be 'void cv::fillPoly(cv::Mat &,const cv::Point **,const int *,int,const cv::Scalar &,int,int,cv::Point)'
1>          C:WorkspaceImageProcessingopencvbuildincludeopencv2/core/core.hpp(2637): or       'void cv::fillPoly(cv::InputOutputArray,cv::InputArrayOfArrays,const cv::Scalar &,int,int,cv::Point)'
1>          while trying to match the argument list '(cv::Mat, cv::Point **, int [1], int, cv::Scalar_<_Tp>)'
1>          with
1>          [
1>              _Tp=double
1>          ]

但是通常你应该能够在函数需要常量指针的地方传递非常量指针,那么为什么它在这里不起作用呢?

当然,我一开始用过Point *ptsp = pts;,我花了相当长的时间和挠头才弄清楚它需要const,这对我来说完全出乎意料。

這裡有解釋 http://www.parashift.com/c++-faq-lite/constptrptr-conversion.html:

从 Foo** 转换→ Foo const** 很危险的原因是,它会让你静默地、意外地修改一个没有强制转换的 const Foo 对象: 类 Foo { 公共: 无效修改(); 对此对象进行一些修改 };

int main()
{
  const Foo x;
  Foo* p;
  Foo const** q = &p;  // q now points to p; this is (fortunately!) an error
  *q = &x;             // p now points to x
  p->modify();         // Ouch: modifies a const Foo!!
  ...
}

如果 q = &p 线是合法的,q 将指向 p。下一行 *q = &x 将 p 本身(因为 q 为 p)更改为指向 x。这将是一件坏事,因为我们会失去 const 限定符:p 是 Foo,但 x 是 const Foo。p->modify() 行利用了 p 修改其引用的能力,这是真正的问题,因为我们最终修改了一个 const Foo。