简体   繁体   English

如何创建仅在C ++中读取一次的初始化函数

[英]How to create a initialization function that only read once in c++

I have this class: 我有这个课:

class A : public B

and i need to add some protected field: _field, in A and I can't touch/change B. Now, all the function in B and A are virtual except the constructor . 并且我需要添加一些受保护的字段:A中的_field,并且我无法触摸/更改B。现在,B和A中的所有函数都是虚拟的, 但构造函数除外 Obviously, _field is not part of class B. 显然,_field不是B类的一部分。

I need to initialize _field. 我需要初始化_field。 How can i do that if the only constructor is B's? 如果唯一的构造函数是B,该怎么办? Also, something like this: 另外,是这样的:

unsigned long _field = 0;

gives me an error compilation. 给我一个错误编译。

I solve this by: 我通过以下方法解决此问题:

class A : public B
{
protected: 
  unsigned long _field;
public:
  void fooFunction(){
     ....do other stuff....
     static bool isInitField = false;
     if (!isInitField){
       _field = 0;
       isInitField = true;
     }
     ...rest of the function...
  }

Is there a better way to do that without using static? 有没有更好的方法可以做到这一点而不使用静态?

Thanks, Or 谢谢,或者

Use A constructor and call B constructor in the initialization list, this way you initialize all fields of class A: 使用A构造函数并在初始化列表中调用B构造函数,这样便可以初始化A类的所有字段:

A(unsigned long i, other_paramaters oth) : B(oth),_field(i) {

}

Pardon me, actually I haven't understood your problem. 对不起,实际上我还不了解您的问题。 As far as one time initialization is concerned, constructor is the place to do it. 就一次初始化而言,构造函数就是这样做的地方。 But your proposed solution hints that you want something else. 但是您提出的解决方案暗示您还需要其他东西。

static in function definition would make _field only one time modifiable across all objects of the class and this is a bit awkward mechanism to make _field one time modifiable. 函数定义中的static将使_field在类的所有对象之间只能被修改一次,这使_field可以被修改一次有点尴尬。

If you want to just initialize _field then use initialization. 如果只想初始化_field,则使用初始化。 Solution by Esteban would do. Esteban的解决方案可以解决。 Better use 更好地使用

A(unsigned long i, other_paramaters oth) : B(oth),_field(i) { } A(无符号长i,other_paramaters oth):B(oth),_ field(i){}

and

A(params):B(params),_field(0){} A(参数):B(参数),_ field(0){}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM