在运行时赋值后只读的变量?
这里是相当新的程序员,并对愚蠢的问题提前致歉。
我在程序中有一个 int 变量,用于确定某些结构中数组的长度。我曾经将它作为 const int 放在我的标头中。现在,我想分叉我的程序,根据给出的参数为变量赋予不同的值,但在运行时分配它后将其保持为只读。
我必须这样做的一些想法。有优选的方式吗?
- 在我的标头中声明一个 const int * 并将其分配给我的主函数中的 const int ,但这看起来很笨拙。
- 在我的 main 函数中将其设为普通的
int
。 - 调用函数时将变量作为参数传递。
- 还有一些我还没想到的事情。
Fairly new programmer here, and an advance apology for silly questions.
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?
- Declare a
const int *
in my header and assigning it to aconst int
in my main function, but that seems clunky. - Make it a plain
int
in my main function. - Pass the variable as an argument when the function is called.
- Something else I haven't thought of yet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会使用函数静态变量和简单函数。观察:
由于这是一个函数级静态变量,因此它仅在第一次初始化。因此,
initialValue
参数在函数第一次运行后就没用了。因此,您需要做的就是确保该函数的第一次调用是对其进行初始化的调用。I'd use a function-static variable and a simple function. Observe:
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.C++ 没有为此提供内置解决方案,但如果您确实想确保 int 只分配一次,您可以构建自己的特殊 int 类:
C++ doesn't have a built-in solution for this, but if you really want to make sure that your int is only assigned once, you can build your own special int class:
您到底什么时候知道正确的值?如果您从文件或其他内容中读取它,您可以直接说:
When exactly do you know the correct value? If you read it from a file or whatever, you can just say:
我很想说你想要的没有意义。常量是指不会改变其值的东西,而不是可能改变其值一次或两次的东西。如果你想要一个全局变量,只需将其设为非常量即可。
另一方面,如果您有作用域常量值,则只需同时声明和初始化它们,遵循一般 C++ 准则来声明尽可能接近使用站点。例如,在以下局部范围中标记常量的使用:
如果变量的值已通过其他方式已知,则编译器甚至可能选择根本不为变量生成任何特殊代码。
I'm tempted to say that what you want doesn't make sense. A constant is something that doesn't change its value, not something that maybe changes its value once or twice. If you want a global variable, just make it non-constant.
On the other hand, if you have scope-constant values, you would just declare and initialize them at the same time, following the general C++ guideline to declare as close to the usage site as possible. For example, mark the use of constants in the following local scope:
Here the compiler may even choose not to generate any special code for the variables at all if their value is already known through other means.