immutable class Foo
{
void bar()
{
}
}
void main()
{
auto x = new Foo();
x.bar();
// Error: function test.Foo.bar () immutable is not callable
// using argument types ()
}
我必须在程序中更改什么才能使 x.bar()
编译? x
的类型是否错误?
最佳答案
看起来像一个错误。 x
被推断为 Foo
类型,虽然它是一个不可变类,但它被视为一个可变变量,这导致 x.bar()
失败,因为 bar()
是一个不可变的方法。
解决方法是提供一个空的不可变构造函数,
immutable class Foo
{
void bar()
{
}
immutable this() {} // <---
}
这导致 new Foo()
表达式返回 immutable(Foo)
。
关于class - 调用不可变类的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11861091/