10

我有一个在运行时永远不会改变的常量值,但直到运行时才知道。

有没有办法在不定义常量的情况下声明一个常量(作为类的成员或不作为一个成员),并且还分配一个计算值一次(并且只有一次)它被确定;还是我将不得不诉诸非常量声明并使用编码标准普尔(ALL_CAPS变量名称,static如果在类中的声明等)来尝试防止它发生变化?

澄清:

尽管这些都是很好的答案,但我的实际情况要复杂得多:

该程序有一个在处理和渲染之间不断运行的主循环;用户可以设置所需的选项,一旦设置,它们将永远不会改变,直到程序重新启动。为在主循环之前可以确定的任何内容设置“初始化”功能,但必须在处理阶段的循环中间执行取决于用户交互的值。(目前,持久性数据存储技术浮现在脑海中......)

4

4 回答 4

10

像这样的东西?

const int x = calcConstant();

如果它是类成员,则使用构造函数初始化列表,如 Yuushi 的回答。

于 2013-01-03T01:28:51.003 回答
10

struct您可以在or中定义它class并使用初始化列表:

#include <iostream>

struct has_const_member
{
    const int x;

    has_const_member(int x_)
      : x(x_)
    { }

};

int main()
{
    int foo = 0;
    std::cin >> foo;
    has_const_member h(foo);
    std::cout << h.x << "\n";
    return 0;
}
于 2013-01-03T01:30:22.140 回答
5

作为静态或函数局部变量:

const int x = calcConstant();

作为班级成员:

struct ConstContainer {
    ConstContainer(int x) : x(x) {}
    const int x;
};
于 2013-01-03T01:30:48.173 回答
1

是的,您可以使用初始化方法和 gettor 方法创建私有静态单例字段。以下是如何执行此操作的示例:

// In foo.h
class Foo
{
public:
    // Caller must ensure that initializeGlobalValue
    // was already called.
    static int getGlobalValue() { 
        if (!initialized) {
            ... handle the error ...
        }
        return global_value; 
    }

    static void initializeGlobalValue(...)

private:
    static bool initialized;
    static int  global_value;
};

// In foo.cpp
bool Foo::initialized = false;
int Foo::global_value;

void Foo::initializeGlobalValue(...) {
    if (initialized) {
        ...handle the error...
    }
    global_value = ...;
    initialized = true;
}
于 2013-01-03T01:35:19.550 回答