[英]Changing default constructor to parameterized
I had a class "SetupModel" with default constructor. 我有一个带有默认构造函数的“ SetupModel”类。 Now I have to include one parameter to this constructor.
现在,我必须在此构造函数中包含一个参数。 So it should be as,
所以应该这样
class SetupModel
{
public:
SetupModel(MyData::ValueSystem& valueSystem);
So I am trying to change all references of this class SetupModel. 因此,我试图更改此类SetupModel的所有引用。
But in another one class this has been called as, 但是在另一类中,这被称为
class SetupManager
{
private:
SetupModel _model;
am getting error "no appropriate default constructor available" 出现错误“没有合适的默认构造函数”
How can I change this? 我该如何更改?
class SetupManager
{
SetupManager(...) : _model(valuesystemarg), ...
{
...
}
private:
SetupModel _model;
Use initializer list to initialize this member. 使用初始化程序列表初始化此成员。
Or add the default parameterless constructor to SetupModel
constructor. 或将默认的无参数构造函数添加到
SetupModel
构造函数。
add a definition of default constructor 添加默认构造函数的定义
class SetupModel
{
public:
SetupModel(MyData::ValueSystem& valueSystem);
SetupModel();
}
You have 2 options in hand 您手边有2个选项
SetupManager
you can define one more constructor within SetupModel
without parameters SetupManager
,你可以定义中的一个多个构造SetupModel
不带参数 class SetupModel { public: SetupModel(MyData::ValueSystem& valueSystem); SetupModel() {};
So you don't need to make change in SetupManager
. 因此,您无需在
SetupManager
进行更改。
SetupModel
constructor with parameters as base class constructor of SetupManager
, you can use initialization list within constructor of SetupManager
. SetupModel
构造函数作为SetupManager
基类构造函数,则可以在SetupManager
构造函数中使用初始化列表。 Then you dont need further change in SetupModel
SetupModel
进一步更改 class SetupManager { SetupManager(...) : _model(valuesystemarg), ... { ... } private: SetupModel _model;
You can have as many constructors as you want but if what you want is to have only one then you can set the default value both in .h or in .cpp 您可以根据需要拥有任意数量的构造函数,但是如果想要的只是一个构造函数,则可以在.h或.cpp中设置默认值。
in .h: 在.h中:
class SetupManager
{
SetupManager() : _model(value), // here you can set all variables u want separated by a coma
private:
SetupModel _model;
}
in cpp: 在cpp中:
SetupManager::SetupManager():
{
_model = value;
}
Be careful so in .h the value is inside "(" and ")" while in cpp you use "=" to assign the value 请注意,在.h中,该值位于“(”和“)”内,而在cpp中,您使用“ =”来分配该值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.