简体   繁体   中英

Preprocess a variable before static initialization list

I want to do a pre-processing activity before I pass a value to an initialization list.

(for example: to do assertion checking)

Here's some context to my question: suppose I have,

1.    class B {
2.    private:
3.         int b_value;
4.    public:
5.         B(int input_of_b) {
6.             b_value = input_of_b;
7.        }
8.    };

and

9.   
10.    class A {
11.    private:
12.        int a_value;
13.        B b_obj
14.    public:
15.         A(int input_value) : b_obj(input_value) {
16.             //A constructor gets called after init list happens
17.        }
18.    };

what if, at line 15; just before I call initialization list to initialize b_obj (b_value) - to input_value

I want to manipulate (do checking or some pre-processing ) the value of input_value ??

How do I achieve this? In Java - there would be something like an initialization block.

I have already thought of -

  1. Making a function external to class A and B, and just before creating an object of A, and initializing it with "input_value", pre-process that value. (However, this violates the loose-coupling concept)

  2. Making a parent class "A's parent" to class A, make class A extend it, do pre-processing in that class, since parent constructor gets called before initialization list? I've not tried this, and I'm not sure if it is the right approach.

I solved this by

making B a pointer, preprocessing the value, and then initializing the B object using new, and then deallocate memory in the destructor

ie

10.    class A {
11.    private:
12.        int a_value;
13.        B* b_obj
14.    public:
15.         A(int input_value) {
16.            //preprocess input_value here
17.            b_obj = new B(input_value);
18.         }
19.         ~A(){
20.            delete b_obj;
21.         }
22.    };

据我了解您的问题,我认为您必须尝试操纵a的构造函数中的输入,然后从该构造函数中使用该输入调用b的构造函数。

Do it in a function!

int b_validate(int);

A::A(int input_value)
    : b_obj(b_validate(input_value))
{}

Also, I'm not initializing a_value because you should remove it instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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