本文介绍了定义类型的正确方法(typedef与#define)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下哪种方法在定义变量类型时更安全?我知道看到#defines时我们都会皱眉,但这似乎和typedef一样有效:
Which of these methods is more secure for defining variable types? I know that we all frown when we see #defines, but it seems to work just as well as typedef here:
一种方法或另一种方法有优势吗?如果可以,那会是什么?
Is there an advantage one way or the other, and if so what might it be?
方法一:
#include <iostream>
#define byte unsigned char
int main() {
byte testByte = 'A';
std::cout << testByte << std::endl;
return 0;
}
方法二:
#include <iostream>
int main() {
typedef unsigned char byte;
byte testByte = 'A';
std::cout << testByte << std::endl;
return 0;
}
推荐答案
You should always use the 2nd one (i.e. typedef or using).
尽量不要在c ++中使用宏,并且可以避免大多数情况.它们只是在编译之前替换文本,更危险".例如
Try to not use macros in c++ as far as possible, and most cases could be avoided. They're just text replacement before compiling, and more "dangerous". e.g.
#define byte_pointer unsigned char*
byte_pointer p, q; // only p is a pointer
这篇关于定义类型的正确方法(typedef与#define)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!