Avoid default constructor for member variable

岁酱吖の 提交于 2019-11-28 12:14:26

问题


I have a class with a member variable of another class:

class MeasurementUnit {
private:
    MeasurementMultiplier _multiplier;

Actually I would not need a default constructor for MeasurementMultiplier, because actually I will initialize with parameters MeasurementMultiplier(a,b,c), and I would - but can't directly:

C2864: 'MeasurementUnit::_multiplier' :
only static const integral data members can be initialized within a class

So I need the default constructor, without it does not compile error: C2512: 'MeasurementUnit' : no appropriate default constructor available

Can I avoid needing the default constructor?


回答1:


In all constructors of your class MeasurementUnit, you need to initialize the member variable _multiplier in the initializer list. Example:

MeasurementUnit::MeasurementUnit()
  : _multiplier(1,2,3)
{}



回答2:


Use MIL - Member Initialization List MIL



来源:https://stackoverflow.com/questions/15420547/avoid-default-constructor-for-member-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!