静态Const对象
Static Const object
我在初始化静态构造结构元素时遇到麻烦。我正在使用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;
}
相关文章:
- 被解释为低级别const的const对象的地址
- 使用共享指针的函数调用,其对象应为 const
- 如何从构造函数副本 T(const T&)调用对象 T?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 无法使用类型 'const char *' 的左值初始化类型 'char *' 的成员子对象
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- "this"指向的对象是否与 const 对象相同?
- const auto & 和 auto & if reference 对象之间的区别是 const
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- C++ - 确定 const char* 是指向字符串文本对象还是动态对象
- 为什么 const YAML::Node 对象的行为不像 yaml-cpp 中的类似值的对象?
- 从 const 对象访问非 const 方法
- 将非 const 对象用于 const 参数
- 如何键入用于const对象的自定义io操纵器
- 对临时对象的Const引用不会延长其生存期
- 正在通过const-ref未定义的行为捕获新构造的对象
- 具有成员变量的对象 Const 数组 = 先前索引成员变量的总和
- 为什么我构建的临时对象const不可变
- 强制用户声明对象const