1

我想用这样的 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;
}

主文件

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};
4

2 回答 2

6

使用<boost/numeric/ublas/assignment.hpp>你可以将值插入到一个ublas::matrixublas::vector使用<<=它允许你像这样实例化你的矩阵:

bnu::matrix<double> a(3,3); a <<=  0, 1, 2,
                                   3, 4, 5,
                                   6, 7, 8;

要使其保持不变,只需复制它:

const bnu::matrix<double> b = a;

这里是一个从这里复制的最小工作示例

于 2018-02-16T07:48:17.417 回答
1

您可以编写一个辅助函数来执行此操作

class Test {
private:
    const bnu::matrix<double> someMatrix;
    static bnu::matrix<double> initSomeMatrix();
public:
    Test();
    virtual ~Test();
}

Test::Test() : someMatrix(initSomeMatrix()) {
}

bnu::matrix<double> Test::initSomeMatrix() {
    bnu::matrix<double> temp(3, 3);
    temp(0,0) = 1;
    ...
    return temp;
}

RVO 应该使这相当有效。

于 2018-02-16T07:38:06.900 回答