C ++ Eigen:子类化向量通过简单操作获得转换错误

时间:2013-05-12 10:34:57

标签: c++ operator-overloading subclass eigen

我已经将Eigen :: Vector2d子类化为一些方便的方法,我不会在这里写(如MyVec.randomize()MyVec.distanceWithThreshold()等。)。

但是当我尝试为新向量分配一些简单的操作时,我面临转换错误。我们来看看我的代码:

#include <iostream>
#include "Eigen/Core"

class Vec2D : public Eigen::Vector2d {
    public:
        Vec2D() : Eigen::Vector2d() {};
        Vec2D(double x, double y) : Eigen::Vector2d(x,y) {}
};

std::ostream& operator<< (std::ostream &out, Vec2D &cPoint) {
    out << "(" << cPoint.x() << ", " << cPoint.y() << ")";
    return out;
}

int main() {
    // test with base class
    Eigen::Vector2d A = Eigen::Vector2d(0,0);
    Eigen::Vector2d B = Eigen::Vector2d(5,5);
    Eigen::Vector2d C = A - B;
    std::cout << C.x() << " " << C.y() << std::endl;

    // test with my subclassed Vec2D
    Vec2D _A,_B;
    _A = Vec2D(0, 0);
    _B = Vec2D(5, 5);
    std::cout << _A-_B << std::endl; // my stream overload is not called
    std::cout << _A << std::endl; // my stream overload is called

    // now the problem
    Vec2D dudeee = _A - _B;            // if I comment this line, no error
    std::cout << dudee << std::endl;  // if I comment this line, no error

    return 0;
}

,错误是:

test.cpp: In function 'int main()':
test.cpp:34: error: conversion from 'const Eigen::CwiseBinaryOp<Eigen::internal::scalar_difference_op<double>, const Eigen::Matrix<double, 2, 1, 0, 2, 1>, const Eigen::Matrix<double, 2, 1, 0, 2, 1> >' to non-scalar type 'Vec2D' requested
test.cpp:35: error: 'dudee' was not declared in this scope

我认为(因为调用我的流操作符重载)在某种程度上我必须覆盖Vec2D中的普通运算符(+, - *,/),以某种方式分配新的Vec2D对象,但是我不知道该怎么做。一些建议?

1 个答案:

答案 0 :(得分:2)

关于编译错误,在C ++构造函数中以及赋值运算符不会自动继承。见doc。特别是你必须重新实现Matrix的所有构造函数&lt;&gt; class,并添加:

using Vector2d::operator=; 

转发赋值运算符。

关于A-B,其类型是CwiseBinaryOp&lt; ...&gt;表达。如果你想让它成为Vec2D,那么你必须施展它:

cout << Vec2D(A-B);

最后,如果您的唯一目的是扩展Eigen的API,那么最好是使用Eigen的plugin插件机制。存在以下插件:

  • EIGEN_DENSEBASE_PLUGIN
    • EIGEN_MATRIXBASE_PLUGIN
      • EIGEN_MATRIX_PLUGIN
    • EIGEN_ARRAYBASE_PLUGIN
      • EIGEN_ARRAY_PLUGIN