c++ 是否提供了一种使整个结构常量(不可修改)的方法?
Does c++ provide a way to make a whole struct constant (non-modifiable)?
到目前为止,我知道我可以将所有结构成员const
。但是我可以在const
的地方写一次,然后让所有成员都转向const
吗?
换句话说,我希望所有结构实例都const
,即使我忘记在变量声明中添加const
修饰符。
const struct Foo {}
由于const can only be specified for objects and functions
错误,上述方法不起作用;
虽然不能创建整个类型const
但可以使用const
限定符为该类型创建别名。
struct Foo {};
using ConstFoo = const Foo;
ConstFoo myFoo; // Same as const Foo myFoo;
在这里,ConstFoo
充当始终const
的类型。
如果您希望将Foo
保留为const
类型,则可以使用
using Foo = const struct {};
相关文章:
- 为什么"具有常量成员的结构"类型的指针不能指向"具有非常量成员的结构"?
- 调用 cout 时如何在结构中输出常量文本?
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 将结构C++成员从非常量转换为常量
- 列出常量和数组结构字段的初始化
- 如何初始化具有常量变量的结构数组
- 常量结构的指针成员
- 如何在C++中声明静态常量结构
- C++常量结构成员初始化
- 命名空间中常量结构、类和数组的初始化
- C++ 更改常量结构的成员值
- 从 C 到 C++ 的常量结构中 char 数组的静态初始化
- 为什么可以在常量结构上调用非常量成员函数
- 正在将常量结构引用转换为非常量指针
- Volatile关键字允许访问UnitTest++中的常量结构
- 类内部的C++常量结构初始化
- c++常量结构初始化
- 在数组声明中使用常量结构成员
- 为什么常量结构数组在按名称引用常量结构时不放在 .rodata 中?
- 在哪里声明常量结构数组