在以下代码中:
class A
{
void aMethod() { }
void aConstMethod() const { }
}
class B
{
const A a; // Not initialized in the constructor, but at a latter time
void initA()
{
a = new A(); // Error: can only initialize const member 'a' inside constructor
}
void doStuff()
{
//a.aMethod(); shouldn't be allowed to call this here, B can only read from A.
a.aConstMethod();
}
}
我希望课程B
只能从const
调用immutable
或A
方法。但是,B
只能在构造后创建A
的实例,因此无法在构造函数中初始化A
。我是否可以修改上述代码,而无需从var const
移除a
?
答案 0 :(得分:3)
class A
{
void aMethod() { }
void aConstMethod() const { }
}
class B
{
import std.typecons: Rebindable;
Rebindable!(const A) a; // Not initialized in the constructor, but at a latter time
void initA()
{
a = new A(); // Error: can only initialize const member 'a' inside constructor
}
void doStuff()
{
static assert(!__traits(compiles, a.aMethod())); // shouldn't be allowed to call this here, B can only read from A.
a.aConstMethod();
}
}