Static struct in C++

拈花ヽ惹草 提交于 2019-12-08 15:41:31

问题


I want to define an structure, where some math constants would be stored.
Here what I've got now:

struct consts {
    //salt density kg/m3
   static const double gamma;
};

const double consts::gamma = 2350;

It works fine, but there would be more than 10 floating point constants, so I doesn't want to wrote 'static const' before each of them. And define something like that:

static const struct consts {
    //salt density kg/m3
   double gamma;
};

const double consts::gamma = 2350;

It look fine, but I got these errors:
1. member function redeclaration not allowed
2. a nonstatic data member may not be defined outside its class

I wondering if there any C++ way to do it?


回答1:


Use a namespace rather than trying to make a struct into a namespace.

namespace consts{
    const double gamma = 2350;
}

The method of accessing the data also has exactly the same synatx. So for example:

double delta = 3 * consts::gamma;



回答2:


It sounds like you really just want a namespace:

namespace consts { 
    const double gamma = 2350.0;
    // ...
}

Except I'd try to come up with a better name than consts for it.



来源:https://stackoverflow.com/questions/3023643/static-struct-in-c

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