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

时间:2016-03-22 10:10:04

标签: 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_;
}

不幸的是,initAinitB无法像上面勾画的那样分开。 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.
}

我希望将a_b_分开(和const)个变量(而不是将它们放在std::tuple或类似的变量中)。但是,我不知道是否可以从单个函数中单独初始化a_b_

任何提示?

3 个答案:

答案 0 :(得分:4)

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

使用委托构造函数:

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_;
};

答案 1 :(得分:2)

我建议看起来很明显,但绝对不需要为成员变量使用const。如果希望类型是不可变的,只需不提供setter方法,并在构造函数中计算成员的值。

class mytest() {
   public:
     mytest() {
         a_ = 1.0 + 1.0;    // some complex computation
         b_ = 2.0 *(a + 1.0);  // another complex computation
         a_ = 2.0 * a_;  // even more complex, wow      
     };

     // Make your methods const to prevent modification of the members
     void testMethod() const {
         // a_ = 20.0; // Will result in an error!
         std::cout << "sum = " << a_ + b_ << '\n'; // perfectly fine
     }

     virtual ~mytest() {};

   private:
       double a_;
       double b_;
};

这更简单,并实现您想要的。

答案 2 :(得分:-1)

你总是可以抛弃常量,但我真的会重新考虑你的设计,而不是去做。

// some pointer
double *ptr;
// give it the value of '_a'
ptr = (double*)( &_a );
// change the value now
*ptr = 5.34;

同样在你的代码中

const double a = 1.0 + 1.0; 

应该是

double a = 1.0 + 1.0; 

不需要它是常量。