我已经将 Eigen::Vector2d 子类化,因为有一些我不会在这里写的方便方法(比如 MyVec.randomize()
、MyVec.distanceWithThreshold()
等..)。
但是当我尝试将一些简单的操作分配给新 vector 时,我遇到了转换错误。让我们看看我的代码:
#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++中,构造函数和赋值运算符都不会自动继承。看这个doc .特别是你必须重新实现 Matrix<> 类的所有构造函数,并添加:
using Vector2d::operator=;
转发赋值运算符。
关于A-B,它的类型是一个CwiseBinaryOp<...>表达式。如果你想让它成为 Vec2D,那么你必须转换它:
cout << Vec2D(A-B);
最后,如果你的唯一目的是扩展 Eigen 的 API,那么最好使用 Eigen 的 plugin插件机制。存在以下插件:
- EIGEN_DENSEBASE_PLUGIN
- EIGEN_MATRIXBASE_PLUGIN
- EIGEN_MATRIX_PLUGIN
- EIGEN_ARRAYBASE_PLUGIN
- EIGEN_ARRAY_PLUGIN
- EIGEN_MATRIXBASE_PLUGIN
关于C++ Eigen : subclassed vector get error in conversion with simple operation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16506467/