【问题标题】:How to override conversion operator in C++ template subclass?如何覆盖 C++ 模板子类中的转换运算符?
【发布时间】:2017-02-12 21:22:42
【问题描述】:

如何覆盖 C++ 模板子类中的转换运算符? 例如,我尝试从 openCv 实现 Rect_ 模板类的子类:

template<typename _Tp> class Rect_
{
public:
    typedef _Tp value_type;

    //! various constructors
    Rect_();
    Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
    Rect_(const Rect_& r);
    Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
    Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);

    Rect_& operator = ( const Rect_& r );
    //! the top-left corner
    Point_<_Tp> tl() const;
    //! the bottom-right corner
    Point_<_Tp> br() const;

    //! size (width, height) of the rectangle
    Size_<_Tp> size() const;
    //! area (width*height) of the rectangle
    _Tp area() const;

    //! conversion to another data type
    template<typename _Tp2> operator Rect_<_Tp2>() const;

    //! checks whether the rectangle contains the point
    bool contains(const Point_<_Tp>& pt) const;

    _Tp x, y, width, height; //< the top-left corner, as well as width and height of the rectangle
};

我的子类 ColorRect 有额外的字段 - 颜色。如何覆盖父类的转换运算符?如果不可能,我可以打电话给转换运营商吗?我该怎么做?

template<typename _Tp> class ColorRect_ : public cv::Rect_<_Tp>
{
    uchar color;

    ColorRect_(): cv::Rect_() { color = NONE; }
    ColorRect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height, uchar color) : cv::Rect_(_x, _y, _width, _height), color(color)
    {

    }

    ColorRect_(const ColorRect_& r) : cv::Rect_(r), color(r.color) {}

    ColorRect_& operator = (const ColorRect_& r)
    {
        cv::Rect_<_Tp>::operator=(r);
        color = r.color;
        return this;
    }

    template<typename _Tp2> operator ColorRect_<_Tp2>() const
    {
        ... ?
    }
};

提前致谢。

【问题讨论】:

  • 不相关但以下划线开头紧跟大写字母的标识符在 C++ 中被保留。

标签: c++ opencv type-conversion operator-overloading operators


【解决方案1】:

您可以创建非显式构造函数来从父实例构造类的实例:

ColorRect_(const cv::Rect_<_Tp>& other) {...};

它的工作方式与转换运算符相同。

【讨论】:

    猜你喜欢
    • 2021-04-21
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多