我的类包含需要使用函数初始化的 const 字段。使用类的静态方法在构造函数的初始化列表中初始化这些值是否合适?
这样做我还没有遇到问题,但是当我读到“静态初始化惨败”时,我担心我忽略了一些稍后会回来咬我的东西,无论哪种方式我都会而是养成正确初始化的习惯。
例子:
方形.hpp:
class Square
{
const double area;
static initArea(double length);
Square(double length);
}
正方形.cpp
Square::initArea(double length)
{
return (length * length);
}
Square::Square(double length) :
area(initArea(length))
{
return;
}
显然我意识到在这种情况下您不需要函数来计算面积,但实际上该函数会确定更复杂的东西。
最佳答案
Is it appropriate to use a static method of the class to initialize these values in the initializer list of the constructor?
是的,这是绝对合适的:静态辅助方法非常适合这项任务,因为它们可以在任何对象的上下文之外运行。因此,在初始化列表中调用它们是完全有效的。
像这样内联一个简单的函数可能也是一个好主意。
关于c++ - 使用静态方法初始化 const 类字段是好事还是坏事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44211882/