如何初始化需要执行计算的const成员? [英] How to initialize const member requiring computations to be performed?

查看:43
本文介绍了如何初始化需要执行计算的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.

这篇关于如何初始化需要执行计算的const成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆