在运行时赋值后是只读的变量吗? [英] A variable that is read-only after assignment at run-time?

查看:64
本文介绍了在运行时赋值后是只读的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的新程序员,以及对愚蠢问题的道歉。

Fairly new programmer here, and an advance apology for silly questions.

我在其中有一个 int 变量我用来确定某些结构中数组长度的程序。我曾经把它作为 const int 放在标题中。现在,我想分叉我的程序,以根据给定的参数为变量提供不同的值,但在运行时分配它后,使其保持只读状态。

I have an int variable in a program that I use to determine what the lengths of my arrays should be in some of my structures. I used to put it in my header as a const int. Now, I want to fork my program to give the variable different values depending on the arguments given in, but keep it read-only after I assign it at run-time.

我不得不这样做的一些想法。有什么首选的方法吗?

A few ideas I've had to do this. Is there a preferred way?


  1. 在标头中声明 const int * 在我的主要功能中将其分配给 const int ,但这似乎很笨拙。

  2. 将其命名为 int 在我的主函数中。

  3. 在调用函数时将变量作为参数传递。

  4. 还有其他事情

  1. Declare a const int * in my header and assigning it to a const int in my main function, but that seems clunky.
  2. Make it a plain int in my main function.
  3. Pass the variable as an argument when the function is called.
  4. Something else I haven't thought of yet.


推荐答案

我会使用函数静态变量并一个简单的功能。观察:

I'd use a function-static variable and a simple function. Observe:

int GetConstValue(int initialValue = 0)
{
  static int theValue = initialValue;
  return theValue;
}

由于这是一个函数级静态变量,因此仅在第一个变量中进行初始化时间流逝。因此 initialValue 参数在函数第一次运行后就没有用了。因此,您需要做的就是确保函数的第一个调用是对其进行初始化的调用。

Since this is a function-level static variable, it is initialized only the first time through. So the initialValue parameter is useless after the first run of the function. Therefore, all you need to do is ensure that the first call of the function is the one that initializes it.

这篇关于在运行时赋值后是只读的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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