問題描述
使用 static const
變量比使用 #define
預處理器更好嗎?或者這取決于上下文?
Is it better to use static const
vars than #define
preprocessor? Or maybe it depends on the context?
每種方法的優點/缺點是什么?
What are advantages/disadvantages for each method?
推薦答案
就個人而言,我討厭預處理器,所以我總是使用 const
.
Personally, I loathe the preprocessor, so I'd always go with const
.
#define
的主要優點是它不需要內存來存儲您的程序,因為它實際上只是用文字值替換一些文本.它還有一個優點是它沒有類型,所以它可以用于任何整數值而不會產生警告.
The main advantage to a #define
is that it requires no memory to store in your program, as it is really just replacing some text with a literal value. It also has the advantage that it has no type, so it can be used for any integer value without generating warnings.
const
"的優點是可以限定范圍,可以在需要傳遞對象指針的情況下使用.
Advantages of "const
"s are that they can be scoped, and they can be used in situations where a pointer to an object needs to be passed.
不過,我不知道您對static
"部分的確切含義.如果您是全局聲明,我會將它放在匿名命名空間中,而不是使用 static
.例如
I don't know exactly what you are getting at with the "static
" part though. If you are declaring globally, I'd put it in an anonymous namespace instead of using static
. For example
namespace {
unsigned const seconds_per_minute = 60;
};
int main (int argc; char *argv[]) {
...
}
這篇關于靜態常量與#define的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!