我想像这样定义一个带有 boost 的常量 3x3 矩阵,它在执行期间永远不会改变:
[1 2 3
4 5 6
7 8 9]
这个矩阵将是一个类的成员。那么,是否可以像原始类型一样,将常量矩阵变量定义并初始化为类成员呢?当我尝试为 someMatrix 变量键入 const 时,我无法在构造函数中分配矩阵数据并收到此错误:
error: assignment of read-only location '((Test*)this)->Test::someMatrix.boost::numeric::ublas::matrix<double>::operator()(0, 0)'
代码如下:
测试.h
#ifndef TEST_H_
#define TEST_H_
#include <boost/numeric/ublas/matrix.hpp>
namespace bnu = boost::numeric::ublas;
class Test {
private:
const double a = 1;
const double b = 2;
const double c = 3;
const double d = 4;
const double e = 5;
const double f = 6;
const double g = 7;
const double h = 8;
const double i = 9;
const bnu::matrix<double> someMatrix;
public:
Test();
virtual ~Test();
};
#endif /* TEST_H_ */
测试.cpp
Test::Test(){
someMatrix(0,0) = a;
}
main.cpp
include "Test.h"
int main() {
Test * t = new Test();
}
我真正想要的是找到一种方法来定义 someMatrix,如下所示:
const bnu::matrix<double> someMatrix(3,3) = {a,b,c,d,e,f,g,h,i};
最佳答案
使用 <boost/numeric/ublas/assignment.hpp>
您可以将值插入 ublas::matrix
或 ublas::vector
使用 <<=
这允许你像这样实例化你的矩阵:
bnu::matrix<double> a(3,3); a <<= 0, 1, 2,
3, 4, 5,
6, 7, 8;
要使其保持不变,只需复制它:
const bnu::matrix<double> b = a;
关于c++ - 带有 boost ublas 的常数矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48821973/