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

问题描述 投票:0回答:1

我知道在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
   }
};

我想知道如何以某种方式扭转这种局面。即,在调用Foo()构造函数的情况下,我想运行一些代码来找出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
   }
};

可以使用构造函数委托来完成此操作吗?

c++ constructor delegating-constructor
1个回答
5
投票

您有两个选择:

  • 将代码从Foo(std::string bar)移动到成员函数,并从Foo()Foo(std::string bar)都调用它。

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

    Foo() : Foo(compute_bar()) {}
    
© www.soinside.com 2019 - 2024. All rights reserved.