C ++:如何将数据成员定义为const

时间:2014-01-19 12:25:03

标签: c++ opencv

我有下面的班级。我希望ROI变量是const成员

class MiniPatch
{
private:
    cv::Mat mimOrigPatch;                                           // Original pixels
    cv::Rect roi; <---- I want it to be const                                               
    int rows;
    int cols;

public:
    MiniPatch(){}
    MiniPatch(cv::Point2i irPos, const cv::Mat &image);
    static const int mnHalfPatchSize = 4;                           // How big is the patch?
};

构造函数的实现如下:

MiniPatch::MiniPatch(cv::Point2i irPos, const cv::Mat & image)
{
  assert(pointInImageRange(image, irPos, mnHalfPatchSize));                             
  roi = cv::Rect(cv::Rect(0, 0, 2 * mnHalfPatchSize + 1, 2 * mnHalfPatchSize + 1));     
  rows = roi.height;
  cols = roi.width;

  cv::Rect region;

  region = roi + irPos - cv::Point2i(irPos.x - roi.width / 2, irPos.y - roi.height / 2); 
  mimOrigPatch = cv::Mat(region.height, region.width, CV_8UC1);                          //define the patch
    image(region).copyTo(mimOrigPatch);                                                  //crop and copy to patch image

}

我的问题是:如何定义此roi变量,使其成为const成员?

感谢

2 个答案:

答案 0 :(得分:1)

  

如何定义这个roi变量,使其成为const成员?

如果const

,则将其声明为MiniPatch成员
class MiniPatch
{
  // as before
  ...

  const cv::Rect roi;
};

初始化后,无法更改const实例。因此,除非默认初始化足够,否则需要在构造函数初始化列表中初始化它:

MiniPatch::MiniPatch(cv::Point2i irPos, const cv::Mat& image)
: roi( /* ctor arguments*/)
{
  rows = roi.height;
  cols = roi.width;
  cv::Rect region ....
  ....
}

答案 1 :(得分:0)

const成员需要直接初始化(ctor-initializer):

typedef int CvRect;
class MiniPatch
{
private:
    const CvRect roi; // Your cv::Rect

public:
    MiniPatch()
    :   roi(1) // Replace 1 by: 0, 0, 2 * mnHalfPatchSize + 1, 2 * mnHalfPatchSize + 1
    {}
};

但是,'const cv :: Rect roi:在你的上下文中总是相同的,可以是静态成员或内联成员函数'static cv :: Rect roi()const'的结果。