[英]C++: const-initialize multiple data members from one initializer function
我有一个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_;
}
不幸的是, initA
和initB
不能像上面描述的那样分开。 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.
}
我想保留a_
和b_
单独的(和const
)变量(而不是将它们放在std::tuple
或类似的变量中)。 但是,我不知道是否可以从单个函数中单独初始化a_
和b_
。
任何提示?
您可以添加额外的中间函数/结构来初始化您的类
与委托构造函数:
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_;
};
我建议看起来似乎很明显,但绝对没有必要为你的成员变量使用const
。 如果希望类型是不可变的,只需不提供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_;
};
这更简单,并实现您想要的。
你总是可以抛弃常量,但我真的会重新考虑你的设计,而不是去做。
// some pointer
double *ptr;
// give it the value of '_a'
ptr = (double*)( &_a );
// change the value now
*ptr = 5.34;
也在你的代码中
const double a = 1.0 + 1.0;
应该
double a = 1.0 + 1.0;
不需要它是const。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.