I have a problem with initialization of a const class member. I have to do many calculations before initialization of the const member, so I can't use this syntax
Class::Class(int value) : value(value) {}
I wish to initialize the member in the constructor body, for example:
Class::Class(int value) {
if (Function1(value)) {
this->value = value;
Function2(&this->value);
}
else
this->value = value * 2;
}
Is it possible? Hope for your help!
Collect all the calculation into a static calculation function.
struct Class {
static int calcValue(int value) {
if (Function1(value) {
Function2(&value);
return value;
}
return value * 2;
}
Class(int val)
: value(calcValue(val))
{}
};
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.