Lew*_*wis 1 c c++ global-variables magic-numbers
我知道并理解全局变量和幻数是编程时要避免的事情,特别是当项目中的代码量增加时.然而,我无法想到一个避免两者的好方法.
Say I have a pre-determined variable representing the screen width, and the value is needed in multiple files. I could do...
doSomethingWithValue(1920);
Run Code Online (Sandbox Code Playgroud)
But that's a magic number. But to avoid that, I'd do...
const int SCREEN_WIDTH = 1920;
//In a later file...
extern const int SCREEN_WIDTH;
doSomethingWithValue(SCREEN_WIDTH);
Run Code Online (Sandbox Code Playgroud)
And now I'm using a global variable. What's the solution here?
Jam*_*lis 11
在你的第二个例子中,SCREEN_WIDTH
它实际上不是变量1,它是一个命名常量.使用命名常量完全没有错.
在C中,如果它是一个整数常量,你可能想要使用枚举,因为const对象不是常量.在C++中,首选使用与原始问题类似的const对象,因为在C++中,const对象是常量.
1.从技术上讲,是的,它是一个"变量",但这个名称并不真正"正确",因为它永远不会改变.
归档时间: |
|
查看次数: |
1806 次 |
最近记录: |