c++ - 使用静态方法初始化 const 类字段是好事还是坏事?

标签 c++ constructor constants static-methods initializer-list

我的类包含需要使用函数初始化的 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/

相关文章:

c# - 在给定指定数量的值后将对象设置为 'read only'

c++ - 递归计算谢尔宾斯基三角形中三角形的数量

c++ - 将void函数输出到txt

c++ - 模板类派生类中的不可访问成员

python - 对于自定义 Python 类,哪个 __repr__ 更好?

Java : Optimize loop of loop with a lot of semi-constant flags checking?

c++ - 如何监控 Linux 的 Wifi 状态

c++ - 使用虚拟继承链接 C++ 构造函数

typescript - Failed to construct 'XMLHttpRequest' : Please use the 'new' operator, 这个DOM对象的构造函数不能作为函数调用

Python:有什么方法可以声明常量参数?