如何初始化需要执行计算的const成员?

如何初始化需要执行计算的const成员?

问题描述:

我知道这是一堂课

class A { 
     const int myint;
  public:
     A (const int yourint);
     A (const std::string yourstring);
};

我可以像这样在初始化列表中初始化 myint :

I could initialize myint in the initializer list like so:

A::A (const int yourint) : myint (yourint) {};

但是,如果从第二个构造函数初始化 myint 的正确方法是,如果计算它所需的数据来自字符串,并且可能涉及到计算,那么该正确方法是什么?

However, what is the proper way of initializing myint from the second constructor if the the data required to compute it comes say from a string and the computations may be involved?

在委托的构造函数的成员初始化列表(如果有的话,不一定需要)中使用函数调用:

Use a function call inside a delegating (if avaliable, not neccessarily) constructor's member initialization list:

A::A(std::string const& yourstring) : A(compute_myint(yourstring)) {};

在您使用时,通过 const& 传递 std :: string ,而不仅仅是 const .

Pass std::string by const&, not just const, while you're at it.

compute_myint 可以是非成员,静态成员,可能无法从类外部访问,以最合理的方式为准.

compute_myint can be non-member, static member, possibly not accessible from outside the class, whichever makes the most sense.