有没有办法判断我们是否在构造函数中被调用?

Is there a way to tell if we're being called inside a constructor?

本文关键字:构造函数 调用 是否 判断 我们 有没有      更新时间:2023-10-16

我想创建一个非静态方法,只有类的同一实例(或其子类之一)的构造函数才能调用。除了面向密钥的访问保护模式之外,还有什么优雅的方法可以做到这一点吗?

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)确保异常得到处理的特殊情况。看到这样,构造函数的事情就是转移注意力。

否。如果没有其他变量告诉你,这是不可能的。你能做的最好的事情是让方法private,这样只有你的类才能调用它。然后确保只有构造函数调用它。除此之外,你只想让构造函数调用它,你有没有尝试过不使用函数,只把代码放在那里?