Static const double in c++

前端 未结 7 423
轮回少年
轮回少年 2021-01-02 07:54

Is this the proper way to use a static const variable? In my top level class (Shape)

#ifndef SHAPE_H
#define SHAPE_H

class Shape
{
public:

    static cons         


        
7条回答
  •  囚心锁ツ
    2021-01-02 08:35

    Static floating-point data members must be defined and initialized in a source file. The one-definition rule forbids a definition outside the class {} block in the header, and only integral data members are allowed to be initialized inside the class {} block.

    This is also unfortunate because, being an algebraic value, having the immediate value on hand could be nice for optimization, rather than loading from a global variable. (The difference is likely to be inconsequential, though.)

    There is a solution, though!

    class Shape
    {
    public:
        static double pi()
            { return 3.14159265; }
    
    private:
        double originX;
        double originY;
    };
    

    Inline function definitions, including static ones, are allowed inside the class{} block.

    Also, I recommend using M_PI from , which you should also get from .

提交回复
热议问题