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

Nur*_*yev 3 c++ struct types const type-declaration

到目前为止,我知道我可以成为所有struct成员const。但是我可以在某个地方写const一次并且所有成员都转向const吗?

换句话说,const即使我忘记const在变量声明中添加修饰符,我也希望所有的struct实例都是这样。

const struct Foo {}
Run Code Online (Sandbox Code Playgroud)

由于const can only be specified for objects and functions错误,以上操作无效;

Fra*_*eux 10

虽然无法创建完整类型,const但是可以使用const限定符为该类型创建别名。

struct Foo {};
using ConstFoo = const Foo;
ConstFoo myFoo; // Same as const Foo myFoo;
Run Code Online (Sandbox Code Playgroud)

在这里,ConstFoo充当的类型始终为const

如果您希望保持Foo作为一个const类型,你可以使用

using Foo = const struct {};
Run Code Online (Sandbox Code Playgroud)

  • 但是`auto`会破坏东西`auto foo2 = myFoo;`:-/ (4认同)