【问题标题】:C++ overload assignment operator of a library class库类的 C++ 重载赋值运算符
【发布时间】:2017-10-07 18:21:35
【问题描述】:

我需要将 cv::Mat 分配给 cv::Point3d

cv::Point3d pt;

cv::Mat mat(3, 1, CV_64F);

pt = mat;

我尝试了两种不同的方式。第一次尝试如下:

template<typename _Tp>
inline cv::Point3_<_Tp> & cv::Point3_<_Tp>::operator = (const cv::Mat & mat){ ... }

但它提供了以下编译错误:

Out-of-line definition of 'operator=' does not match any declaration in 'Point3_<_Tp>'

我也尝试了这个不同的解决方案:

 template<typename _Tp>
 inline cv::Mat::operator cv::Point3_<_Tp>() const { }

但是,编译器不喜欢它并提供以下错误:

Out-of-line definition of 'operator Point3_<type-parameter-0-0>' does not match any declaration in 'cv::Mat'

我错过了什么?

【问题讨论】:

  • 为什么不做一个免费的功能cv::Point3d create_point(cv::Mat const&amp; mat)?然后你可以说cv::Point3d pt = create_point(mat);
  • 因为我更喜欢避免显式调用函数作为 create_point()

标签: c++ opencv operator-overloading assignment-operator


【解决方案1】:

您不能在类定义之外定义赋值或转换运算符。他们必须是members of the class

你可以做的是提供你自己的包装类来允许这样的分配。比如:

namespace mycv
{
    class Point3d
    {
    public:
        template <typename... Args>
        Point3d(Args&& ... args)
            : value(std::forward(args)...)
        {}

        Point3d& operator=(cv::Mat const& mat)
        {
            // do your stuff;
            return *this;
        }

        operator cv::Point3d() const
        {
            return value;
        }

    private:
        cv::Point3d value;
    };
}

int main(int argc, const char* argv[])
{
    mycv::Point3d pt;
    cv::Mat mat;
    pt = mat;
}

【讨论】:

  • 太糟糕了,但感谢您的回答。无论如何,为什么这是不可能的?
猜你喜欢
  • 2013-03-30
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 2018-12-27
  • 2013-08-10
  • 2012-04-22
  • 2015-06-01
相关资源
最近更新 更多