c++ - 静态常量对象

标签 c++ static struct initialization constants

我在初始化静态常量结构元素时遇到问题。我正在使用 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。我无法让 static const poly_mat IDENTITY 行工作,所以现在我有一个函数 return_id() 输出单位矩阵,但我不想每次想返回时都计算一个新的单位矩阵

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

谢谢。

最佳答案

迈耶斯建议采用这种方法。只需像您所做的那样使用函数,但在函数中创建局部变量 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;
}

关于c++ - 静态常量对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17157112/

相关文章:

c++ - 与 C++ 中的指针相关的静态类型类

使用堆栈的 C/C++ 算术表达式求值

go - 将 Spanner 行字段解码为嵌套结构golang

c++ - 带指针的 void 函数

c++ - 这些行号在此错误中意味着什么?

c++ - 堆栈.h :13:3: error: ‘Cell’ does not name a type

c++ - 类和结构,没有默认构造函数

c++ - 在 GLFW 中抓取鼠标光标

java - 使用静态作为对象时出现空指针异常?

c# - 未使用的常量是否仍被编译或优化掉?如果没有,如何实现?