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

时间:2013-07-25 16:52:38

标签: c++

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

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)确保处理异常的特殊情况。看起来像这样,构造函数是一个红色的鲱鱼。

1 个答案:

答案 0 :(得分:5)

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