How to define a const double inside a class's header file?

梦想与她 提交于 2019-11-29 18:04:36

问题


Inside the header file of my class, I am trying the following and getting compiler complaints:

private:
    static const double some_double= 1.0;

How are you supposed to actually do this?


回答1:


In C++11, you can have non-integral constant expressions thanks to constexpr:

private:
    static constexpr double some_double = 1.0;



回答2:


Declare it in the header, and initialize it in one compilation unit (the .cpp for the class is sensible).

//my_class.hpp
private:
static const double some_double;

//my_class.cpp
const double my_class::some_double = 1.0;



回答3:


I've worked around this issue by doing this:

//my_class.hpp
const double my_double() const {return 0.12345;}

//in use
double some_double = my_class::my_double();

I got the idea from

math::pi()


来源:https://stackoverflow.com/questions/8440213/how-to-define-a-const-double-inside-a-classs-header-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!