1

我在初始化静态 const 结构元素时遇到问题。我正在使用 NTL 的多项式 mod p (ZZ_pX.h) 库,我需要以下结构:

struct poly_mat {
    ZZ_pX a,b,c,d;
    void l_mult(const poly_mat& input); // multiplies by input on the left
    void r_mult(const poly_mat& input); // multiplies by input on the right

    static const poly_mat IDENTITY;  // THIS IS THE PART I AM HAVING TROUBLE WITH
}

所以 poly_mat 是一个 2x2 多项式矩阵。我有乘法运算,在我编写的函数中,我经常必须返回单位矩阵 a=1,b=0,c=0,d=1。我无法让静态 const poly_mat IDENTITY 行工作,所以现在我有一个函数 return_id() 可以输出单位矩阵,但我不想每次我想返回时都计算一个新的单位矩阵它。

有没有办法在我的 cpp 文件中初始化静态 const poly_mat IDENTITY,这样我就可以只引用单位矩阵的相同副本,而不必每次都生成一个新副本。矩阵元素是多项式 mod p,并且直到我的 int main() 的第一行才选择 p,这一事实使情况变得复杂。也许我必须使 IDENTITY 成为指向某物的指针并在我设置 p 后对其进行初始化?那么 IDENTITY 可以是静态常量吗?我说得有道理吗?

谢谢。

4

1 回答 1

1

Meyers 提出了这种方法。只需像您所做的那样使用一个函数,但在函数中创建局部变量static并返回对它的引用。 static确保只创建一个对象。

这是一个示例,显示theIdentity()每次返回相同的对象。

#include <iostream>

struct poly_mat {
  int x;
  static const poly_mat & TheIdentity();
};

const poly_mat & poly_mat::TheIdentity() {
  static struct poly_mat theIdentity = {1};
  return theIdentity;
}

int main()
{
  std::cout << "The Identity is " << poly_mat::TheIdentity().x 
    << " and has address " << &poly_mat::TheIdentity() << std::endl;
  struct poly_mat p0 = {0};
  struct poly_mat p1 = {1};
  struct poly_mat p2 = {2};
  std::cout << "The Identity is " << p0.TheIdentity().x 
    << " and has address " << &p0.TheIdentity() << std::endl;
  std::cout << "The Identity is " << p1.TheIdentity().x 
    << " and has address " << &p1.TheIdentity() << std::endl;
  std::cout << "The Identity is " << p2.TheIdentity().x 
    << " and has address " << &p2.TheIdentity() << std::endl;
  return 0;
}
于 2013-06-17T23:13:29.090 回答