转发声明cv::Mat

Forward declaration cv::Mat

本文关键字:Mat cv 声明 转发      更新时间:2023-10-16

嗨,我正在尝试转发声明cv::Mat类,但我无法使其工作。它给出消息字段'frame'的类型不完整

OpenGlImpl.h

namespace cv {
    class Mat;
}
class OpenGLImpl {
private:
   cv::Mat frame;
};

我应该如何正确转发声明?

此处不能使用正向声明。编译器需要有cv::Mat的定义,才能成为OpenGLImpl的数据成员。

如果你想避免这种限制,你可以让OpneGLImpl持有一个指向cv::Mat:的(智能)指针

#include <memory>
namespace cv {
    class Mat;
}
class OpenGLImpl {
private:
   std::unique_ptr<cv::Mat> frame;
};

然后,您可以在实现文件中实例化unique_ptr所拥有的cv::Mat

请注意,引用也可以使用正向声明,但这里不太可能需要引用语义。

§3.9.5

已声明但未定义的类,或大小未知或元素类型不完整的数组,都是不完全定义的对象类型。43不完全定义对象类型和void类型都是不完整类型(3.9.1)。对象不应定义为具有不完整类型

struct X; // X is an incomplete type
X* xp;    // OK, xp is a pointer to an incomplete type. 
struct Y
{
   X x;   // ill-formed, X is incomplete type
}     
struct Z
{
   X* xp;   // OK, xp is a pointer to an incomplete type
}     

void foo() {
//  xp++; // ill-formed: X is incomplete
}
struct X { int i; }; // now X is a complete type
X x;           // OK, X is complete type, define an object is fine
void bar() {
  xp = &x;     // OK; type is “pointer to X”
}
void t()
{   
  xp++; // OK: X is complete
}