Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 444
zebra Avatar asked Dec 09 '11 02:12

zebra


Video Answer


3 Answers

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

private:
    static constexpr double some_double = 1.0;
like image 197
Kerrek SB Avatar answered Nov 03 '22 22:11

Kerrek SB


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;
like image 35
twsaef Avatar answered Nov 03 '22 23:11

twsaef


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()
like image 28
covstat Avatar answered Nov 03 '22 21:11

covstat