C ++构造函数委派,但是如何(某种程度上)反转?

Neu*_*tar 0 c++ constructor delegating-constructor

我了解在C ++ 11中,构造函数委托可以如下所示:

class Foo
{
 public:
  Foo()
   {
     // Some code to be ran first
   }
  Foo(std::string bar): Foo() // Runs the code to be ran first
   {
    // Some code to be ran second, presumably using bar
   }
};
Run Code Online (Sandbox Code Playgroud)

我想知道如何以某种方式扭转这种局面。也就是说,在Foo()调用构造函数的情况下,我想运行一些代码来找出a的值,std::string然后将其用于Foo(std::string bar)完成初始化。因此,Foo()它同时运行自己的代码和中的代码Foo(std::string bar),而后者仅运行自己的代码,例如

class Foo
{
 public:
  Foo()
   {
     std::string bar_figured_out;
     // Figures out the value for bar_figured_out

     Foo(bar_figured_out); // I know this wouldn't work, just an example of what I'm trying to do.
   }
  Foo(std::string bar):
   {
    // Some code to finish class initialization, using bar
   }
};
Run Code Online (Sandbox Code Playgroud)

有什么方法可以使用构造函数委托来实现?

Hol*_*Cat 6

您有两种选择:

  • 从移动代码Foo(std::string bar)成员函数,以及来自调用它Foo()Foo(std::string bar)

  • 将确定的值的代码移至bar_figured_out成员函数,然后Foo()在委派给时调用该函数Foo(std::string bar)

    Foo() : Foo(compute_bar()) {}
    
    Run Code Online (Sandbox Code Playgroud)