[英]C++: const-initialize multiple data members from one initializer function
I have a C++ class with two data members, eg, 我有一个C ++类,有两个数据成员,例如,
class mytest() {
public:
mytest():
a_(initA()),
b_(initB())
{};
virtual ~mytest() {};
private:
double initA() {
// some complex computation
}
double initB() {
// some other complex computation
}
private:
const double a_;
const double b_;
}
Unfortunately, though, initA
and initB
cannot be separated as sketched above. 不幸的是,
initA
和initB
不能像上面描述的那样分开。 Both a_
and b_
can be initialized by one big complex computation, where the value of b_
depends on an intermediate result in the computation of a_
, eg, a_
和b_
都可以通过一个大的复杂计算来初始化,其中b_
的值取决于a_
的计算中的中间结果,例如,
void mytest::init() const {
const double a = 1.0 + 1.0; // some complex computation
const double b = 2*(a + 1.0); // another complex computation
a = 2 * a; // even more complex, wow
// Now, a and b contain the data from which a_ and b_ should be initialized.
}
I would like to keep a_
and b_
separate (and const
) variables (and not put them in a std::tuple
or similar). 我想保留
a_
和b_
单独的(和const
)变量(而不是将它们放在std::tuple
或类似的变量中)。 However, I don't know if it's possible to initialize a_
and b_
separately from a single function. 但是,我不知道是否可以从单个函数中单独初始化
a_
和b_
。
Any hints? 任何提示?
You can add extra intermediate function/struct to initialize your class 您可以添加额外的中间函数/结构来初始化您的类
with delegating constructor: 与委托构造函数:
struct MytestHelper
{
double a;
double b;
};
MytestHelper someComplexComputation(); // feed `a` and `b`
class mytest() {
public:
mytest() : mytest(someComplexComputation()) {}
virtual ~mytest() {};
private:
mytest(const MytestHelper& h) : a_(h.a), b_(h.b) {}
private:
const double a_;
const double b_;
};
What I will suggest may seem obvious, but there is absolutely no need to use const
for your member variables. 我建议看起来似乎很明显,但绝对没有必要为你的成员变量使用
const
。 If you want your type to be immutable, simply do not provide setter methods, and compute the values of your members in the constructor. 如果希望类型是不可变的,只需不提供setter方法,并在构造函数中计算成员的值。
class mytest() {
public:
mytest() {
a_ = 1.0 + 1.0; // some complex computation
b_ = 2.0 *(a + 1.0); // another complex computation
a_ = 2.0 * a_; // even more complex, wow
};
// Make your methods const to prevent modification of the members
void testMethod() const {
// a_ = 20.0; // Will result in an error!
std::cout << "sum = " << a_ + b_ << '\n'; // perfectly fine
}
virtual ~mytest() {};
private:
double a_;
double b_;
};
This is much simpler, and achieves what you want. 这更简单,并实现您想要的。
You can always cast away the constness, but I would really reconsider your design rather than doing it. 你总是可以抛弃常量,但我真的会重新考虑你的设计,而不是去做。
// some pointer
double *ptr;
// give it the value of '_a'
ptr = (double*)( &_a );
// change the value now
*ptr = 5.34;
Also in your code 也在你的代码中
const double a = 1.0 + 1.0;
Should be 应该
double a = 1.0 + 1.0;
No need for it to be const. 不需要它是const。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.