用简单的操作转换子类向量时得到错误



我已经子类化了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对象,但我不知道该怎么做。一些建议吗?

关于编译错误,在c++中构造函数和赋值操作符不会自动继承。看看这个医生。特别是,您必须重新实现Matrix<>类的所有构造函数,并添加:

using Vector2d::operator=; 

转发赋值操作符。

关于a - b,它的类型是CwiseBinaryOp<…>表达式。如果你想要它是一个Vec2D,那么你必须强制转换它:

cout << Vec2D(A-B);

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

  • EIGEN_DENSEBASE_PLUGIN
    • EIGEN_MATRIXBASE_PLUGIN
      • EIGEN_MATRIX_PLUGIN
    • EIGEN_ARRAYBASE_PLUGIN
      • EIGEN_ARRAY_PLUGIN

最新更新