在下面的代码中:
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
只能从 A
调用 const
或 immutable
方法。但是,B
只能在构造完成后才能创建 A
的实例,因此无法在构造函数中初始化 A
。我可以在不从 var a
中删除 const
的情况下修复上面的代码吗?
最佳答案
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();
}
}
关于d - 在构造函数之外初始化 const 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24668243/