C++:从一个初始化函数中初始化多个数据成员

Nic*_*mer 6 c++ initialization

我有一个C++类,有两个数据成员,例如,

class mytest() {
   public:
     mytest():
        a_(initA()),
        b_(initB())
     {};
     virtual ~mytest() {};

   private:
     double initA() {
        // some complex computation
     }
     double initB() {
        // some other complex computation
     }

   private:
       const double a_;
       const double b_;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,虽然,initA并initB不能像上面勾画的那样分开.二者a_并b_可以由一个大的复杂的计算,其中的值被初始化b_取决于中间结果中的计算a_,例如

void mytest::init() const {
   const double a = 1.0 + 1.0;    // some complex computation
   const double b = 2*(a + 1.0);  // another complex computation
   a = 2 * a;  // even more complex, wow
   // Now, a and b contain the data from which a_ and b_ should be initialized.
}
Run Code Online (Sandbox Code Playgroud)

我想保留a_和b_分离(和const)变量(而不是将它们放在一个std::tuple或类似的变量中).但是,我不知道是否可以初始化a_并b_单独使用单个函数.

任何提示?

Jar*_*d42 5

您可以添加额外的中间函数/结构来初始化您的类

使用委托构造函数:

struct MytestHelper
{
    double a;
    double b;
};

MytestHelper someComplexComputation(); // feed `a` and `b`

class mytest() {
   public:
     mytest() : mytest(someComplexComputation()) {}
     virtual ~mytest() {};

   private:
     mytest(const MytestHelper& h) : a_(h.a), b_(h.b) {}

   private:
       const double a_;
       const double b_;
};
Run Code Online (Sandbox Code Playgroud)

  • 杰出的!在“计算机科学中的所有问题都可以通过添加另一个间接层(除了太多的间接层)来解决”的(长)列表中添加另一个示例。 (2认同)