静态Const对象

Static Const object

本文关键字:对象 Const 静态      更新时间:2023-10-16

我在初始化静态构造结构元素时遇到麻烦。我正在使用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()输出的身份矩阵,但我不想计算一个新的身份矩阵,每次我想返回它。

是否有一种方法来初始化静态const poly_mat IDENTITY在我的cpp文件,这样我就可以只是引用相同的副本的身份矩阵,而不是每次生成一个新的。它是复杂的,因为矩阵元素是多项式mod p, p直到我的int main()的第一行才被选中。也许我需要让IDENTITY成为一个指向某个东西的指针并在设置p后对其进行初始化?那么IDENTITY可以是静态const吗?我说的有道理吗?

谢谢。

这种方法是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;
}