C++ Assign a const value at run-time?

蹲街弑〆低调 提交于 2019-12-05 03:34:40

Something like this?

const int x = calcConstant();

If it's a class member, then use the constructor initialisation list, as in Yuushi's answer.

You can define it in a struct or class and utilize an initialisation list:

#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;
}

As a static or function-local variable:

const int x = calcConstant();

As a class member:

struct ConstContainer {
    ConstContainer(int x) : x(x) {}
    const int x;
};

Yes, you can make a private static singleton field with an initialization method and a gettor method. Here's an example of how to do it:

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