首页 > 解决方案 > 在没有初始化的情况下委托构造函数

问题描述

我正在尝试在没有初始化的情况下实现委托构造函数。这是因为我需要通过函数调用获得的适当值。如何在不重复代码的情况下编写正确的代码?

class foo
{
  private:
    // Something
  public:
    foo() = delete;
    foo(double a, double b, double c) 
    {
    // Something
    }
    foo(int n)
    {
    double a, b, c;
    // a, b, c passed by reference and appropriate value is obtained here.
    function_call(n, a, b, c); 
    // construct this object as if the call is foo(a, b, c) now
    foo(a, b, c); // ??? Does this work?
    }
};

标签: c++11

解决方案


foo(a, b, c); // ??? Does this work?

不,它不起作用。它创建了一个临时对象,并且无法初始化当前对象的成员变量。

我的建议:

更改function_call为返回 astd::tuple<double, double, double>而不是更新通过引用传递的对象的值。

然后,您可以使用:

class foo
{
   private:

      foo(std::tuple<double, double, double> const& t) : foo(std::get<0>(t), std::get<1>(t), std::get<2>(t)) {}

   public:

      foo() = delete;

      foo(double a, double b, double c) 
      {
         // Something
      }

      foo(int n) : foo(function_call(n)) {}

};

您也可以将std::array<double, 3>其用作构造函数的返回值function_call并相应地更新构造函数。

foo(std::array<double, 3> const& arr) : foo(arr[0], arr[1], arr[2]) {}

推荐阅读