我想做一个非静态方法,只有类的同一个实例(或它的一个子类)的构造函数可以调用。有没有一种优雅的方式来做到这一点,缺少面向密钥的访问保护模式?有没有办法告诉我们是否在构造函数中被调用?
class MyClass
{
public:
void foo()
{
assert(foo was called from the constructor); //how?!
if (some condition or other)
throw ExceptionThatOnlyClientsThatConstructTheObjectCanHandle(); //hence my requirement
}
};
class MySubClass : public MyClass
{
public:
MySubClass()
{
blah(); //correct use of foo() through blah()
foo(); //correct use of foo() directly
}
void blah() { foo(); } //correctness depends on who called blah()
};
int main()
{
MySubClass m;
m.foo(); // incorrect use of foo()
m.blah(); // incorrect use of foo() through blah()
return 0;
}
编辑:看我下面的意见,但我认为这是(1)面向传递密钥访问控制或(2)确保异常处理的特殊情况。看到这样,构造函数是一个红色的鲱鱼。
首先,使它不被公开。这无助于确定构造函数是否调用它,但至少该类的用户将无法访问它。至于你的问题的核心,我相信最好的是依靠程序员的善意。 – syam
您是否知道基类初始化程序和委托构造函数?他们可以为你想要做的任何事情服务。 – Sneftel
因为'blah'调用'foo',所以唯一允许看到'blah'的函数应该是class,因此'blah'应该是private的。你不能将'foo'的代码移动到'MyClass'的构造函数中吗? – stefan