C ++中的静态结构 [英] Static struct in C++

查看:405
本文介绍了C ++中的静态结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个结构,其中会存储一些数学常数。

现在我已经有了:

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;

它工作正常,但会有超过10个浮点常数,因此我不想在每个人之前写static const。并定义如下:

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;

看起来不错,但我遇到了这些错误:

1.成员函数不允许重新声明

2.非静态数据成员不能在其类之外定义

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

我想知道是否有任何C ++方法? / p>

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

推荐答案

使用命名空间,而不是试图将结构体变成命名空间。

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

namespace consts{
    const double gamma = 2350;
}

访问数据的方法也有完全相同的synatx。例如:

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

double delta = 3 * consts::gamma;

这篇关于C ++中的静态结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆