静态Const对象

时间:2013-06-17 21:23:10

标签: c++ static struct initialization const

我在初始化静态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可以是静态const吗?我有道理吗?

感谢。

1 个答案:

答案 0 :(得分: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;
}
相关问题