C ++在运行时分配const值吗? [英] C++ Assign a const value at run-time?

查看:91
本文介绍了C ++在运行时分配const值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a constant value that never changes during run-time, but is impossible to know until run-time.

有没有一种声明常量的方法(要么作为一个类的成员,要么不作为一个类的成员)而没有定义它,并且还一次(仅一次)确定了计算值;还是我不得不诉诸非const声明并使用编码S& Ps( ALL_CAPS 变量名称, static 声明,如果在类中,等等。) try 并使其保持不变?

Is there a way to declare a constant (either as a member of a class or not) without defining it and also assign a computed value once (and only once) it is determined; or am I going to have to resort to a non-const declaration and use coding S & Ps (ALL_CAPS variables names, static declaration if in a class, etc.) to try and keep it from changing?

澄清:

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

Though these are good answers, the real-world situation I have is more complicated:

该程序有一个主循环,该循环在处理和渲染之间连续运行;用户可以设置所需的选项,并且一旦设置,它们将不会更改,直到重新启动程序。对于在主循环之前可以确定的任何内容,都设置了初始化功能,但是取决于用户交互的值必须在处理阶段的循环中间执行。 (此刻,我想到了持久性数据存储技术...)

The program has a main loop that continually runs between processing and rendering; the user can set required options and once they are set they will never change until the program is restart. An "Initialize" function is set up for anything that can be determined before the main loop, but values that are dependent on user interaction must be performed in the middle of the loop during the processing phase. (At the moment, persistent data storage techniques come to mind...)

推荐答案

类似的东西?

const int x = calcConstant();

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

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

这篇关于C ++在运行时分配const值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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