简体   繁体   English

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

[英]C++: const-initialize multiple data members from one initializer function

I have a C++ class with two data members, eg, 我有一个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_;
}

Unfortunately, though, initA and initB cannot be separated as sketched above. 不幸的是, initAinitB不能像上面描述的那样分开。 Both a_ and b_ can be initialized by one big complex computation, where the value of b_ depends on an intermediate result in the computation of a_ , eg, 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.
}

I would like to keep a_ and b_ separate (and const ) variables (and not put them in a std::tuple or similar). 我想保留a_b_单独的(和const )变量(而不是将它们放在std::tuple或类似的变量中)。 However, I don't know if it's possible to initialize a_ and b_ separately from a single function. 但是,我不知道是否可以从单个函数中单独初始化a_b_

Any hints? 任何提示?

You can add extra intermediate function/struct to initialize your class 您可以添加额外的中间函数/结构来初始化您的类

with delegating constructor: 与委托构造函数:

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

What I will suggest may seem obvious, but there is absolutely no need to use const for your member variables. 我建议看起来似乎很明显,但绝对没有必要为你的成员变量使用const If you want your type to be immutable, simply do not provide setter methods, and compute the values of your members in the constructor. 如果希望类型是不可变的,只需不提供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_;
};

This is much simpler, and achieves what you want. 这更简单,并实现您想要的。

You can always cast away the constness, but I would really reconsider your design rather than doing it. 你总是可以抛弃常量,但我真的会重新考虑你的设计,而不是去做。

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

Also in your code 也在你的代码中

const double a = 1.0 + 1.0; 

Should be 应该

double a = 1.0 + 1.0; 

No need for it to be const. 不需要它是const。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用C ++类中的复杂函数初始化const成员 - Initialize const members using complex function in C++ class 在C ++中的类初始值设定项中初始化const数组 - initialize a const array in a class initializer in C++ 使用一个 function 调用 C++ 初始化多个常量 class 成员 - Initialize multiple constant class members using one function call C++ 使用函数中的数据初始化C ++ const成员(MPI_comm_size / rank) - Initializing C++ const members with data from function (MPI_comm_size/rank) 将成员 function arguments 初始化为 c++ 中的数据成员 - Initialize member function arguments as data members in c++ C ++数据成员。 目标:在构造函数中初始化然后不理会,const在这里可以工作吗? - C++ data members. Goal: Initialize in constructor then leave alone, will const work here? 成员初始化列表:从返回元组的函数初始化两个成员 - Member initializer list: initialize two members from a function returning a tuple const object 还是 C++ 中的私有/常量数据成员(变量)? - const object or private/const data members (variables) in C++? 将C ++ struct成员从非const转换为const - Convert C++ struct members from non-const to const C++ class 一次赋值初始化多个数据成员 - C++ class initialization of multiple data members with one assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM