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

标签 c++

我想制作一个非静态方法,只有该类(或其子类之一)的同一实例的构造函数才能调用。除了面向 key 的访问保护模式之外,是否有一种优雅的方式来做到这一点?

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) 可传递的面向 key 的访问控制或 (2) 确保处理异常的特例。这么看来,构造函数是一个转移注意力的东西。

最佳答案

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

关于c++ - 有没有办法判断我们是否在构造函数中被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17864116/

相关文章:

c++ - 创建没有字符串库的字符串类

c++ - 阅读 CF、PF、ZF、SF、OF

c++ - 进程返回 255 (0xff) 个代码块

c++ - sql连接?

c++ - 如何在没有复制构造函数的情况下为 map 设置值?

c++ std::sort a std::vector 使用函数返回值

c++ - 如何让 YouCompleteMe 突出显示错误和警告?

android - 将图像从 ios/c++ 代码传递到 JNI Android

C++ - 将项目添加到排序数组的最快方法

C++成员函数的多重定义,基于枚举模板参数