1

我想使用一个全局变量n = 7来初始化一个7x7单位矩阵,如下面的代码所示:

#include <iostream>
#include <Eigen/Dense>

using namespace std;
using namespace Eigen;
using Eigen::MatrixXd;

int n = 7;

int main()
{
        MatrixXd I = Matrix<double, n, n>::Identity();
        cout << I << endl;
}

编译时,我得到error: the variable n is not usable in a constant expression. 有没有办法使用全局变量来初始化单位矩阵?

4

1 回答 1

2

如错误消息所述,您需要一个编译时间常数。

你可以n通过使用constexpr

#include <iostream>
#include <Eigen/Dense>

using namespace std;
using namespace Eigen;
using Eigen::MatrixXd;

constexpr int n = 7;

int main()
{
        MatrixXd I = Matrix<double, n, n>::Identity();
        cout << I << endl;
}
于 2021-06-24T18:53:52.140 回答