如何在 C++ 中做到这一点?
//java example
public class MyImmutable {
private final int numToBeInitializedOnConstructionOrCompilationError;
public MyImmutable(int n) {
this.numToBeInitializedOnConstructionOrCompilationError = n;
}
}
对于Java,如果final属性在声明时或构造函数上未初始化,编译器将出错,此代码可以工作,因为成员变量是在构造函数中初始化的。如何在 C++ 中的类声明中强制不变性?
(仅定义公共 getter 方法不是一个可接受的答案,我知道“const”必须是解决方案的一部分)
如果我在 C++ 中这样做:
class MyImmutable
{
private:
const int numToBeInitializedOnConstruction;
public:
MyImmutable(int n);
};
MyImmutable::MyImmutable(int n)
{
numToBeInitializedOnConstruction = n;
}
我收到以下错误,基本上告诉我我无法分配const成员,所以我猜const比java的'final'更严格,是否还有另一个关键字或者有没有办法在声明const后初始化它?
$ gcc const.cc
const.cc:10:10: error: constructor for 'MyClass' must explicitly initialize the const member
'numToBeInitializedOnConstruction'
MyClass::MyClass(int n) {
^
const.cc:3:13: note: declared here
const int numToBeInitializedOnConstruction;
^
const.cc:11:36: error: read-only variable is not assignable
numToBeInitializedOnConstruction = n;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
2 errors generated.
那么如何在 C++ 中声明与 Java Final 成员变量等效的内容呢?这可能吗?
C++ 可以比 Java 更好的方式处理对象不变性。首先,您可以使用
const
限定符从几乎任何类型创建不可变对象。
const string str = "asd";
const MyClass myObj(1);
您也可以拥有像
numToBeInitializedOnConstruction
那样的常量属性,但它必须在构造函数的成员初始化列表中初始化,如下所示:
MyImmutable::MyImmutable(int n)
: numToBeInitializedOnConstruction(n) // like this
{
}
使用初始化列表,例如:
MyImmutable::MyImmutable(int n):
numToBeInitializedOnConstruction(n)
{}
编辑:只是更好的缩进。
要声明一个不可变的对象,只需将其声明为
const
:
const Foo myImmutableFoo;
要声明类的不可变属性,您可以声明这些成员
const
——但是您没有使用正确的语法来初始化它们。给定:
class Foo
{
const int mImmutableN;
public:
Foo();
};
你不能在构造函数体内初始化
mImmutableN
;它必须在构造函数的初始化列表中初始化:
Foo::Foo()
:
mImmutableFoo (42)
{
}