c++ 是否提供了一种使整个结构常量(不可修改)的方法?

Does c++ provide a way to make a whole struct constant (non-modifiable)?

本文关键字:常量 结构 修改 方法 是否 c++ 一种      更新时间:2023-10-16

到目前为止,我知道我可以将所有结构成员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 {};