简体   繁体   English

如何在类的头文件中定义const double?

[英]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? 你怎么这么做呢?

In C++11, you can have non-integral constant expressions thanks to constexpr : 在C ++ 11中,由于constexpr ,你可以使用非整数常量表达式:

private:
    static constexpr double some_double = 1.0;

Declare it in the header, and initialize it in one compilation unit (the .cpp for the class is sensible). 在头文件中声明它,并在一个编译单元中初始化它(该类的.cpp是合理的)。

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

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

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM