#定义文件类型
是
#define LBitmap std::list < CBITMAP *>
一个好的做法吗?
编辑: 好吧,我该怎么做才能让我的老板相信这是不好的做法呢?
Is
#define LBitmap std::list < CBITMAP *>
a good practice?
Edit:
Allright, what can I do to convince my boss that this is bad practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,在 C++ 中使用 #define 不是一个好习惯。
使用 typedef 是有好处的,因为它有一个明确定义的范围
typedef 是定义范围的,编译器每次遇到它时都会解释它的定义,而 #define 则不然。 #define 被解释为编译时间本身。
以下是 typedef 和 #define 的 MSDN 定义
typedef 声明引入了一个名称,在其范围内,该名称成为声明的类型声明部分给出的类型的同义词。
当使用 DEFINE 语句时,该语句的所有实例都将被替换通过预处理阶段语句的值。
说服你的老板
CHARPTR a, b
;预处理后,该行扩展为
Here, only variable a is of type char * while b is simple char
如果您使用 typedef
Here a 和 b 都是 char * 类型
No, its not a good practice to use #define in C++.
Its good to use typedef as this has a well defined scope
typedef is scope defined and compiler interprets its definition each time it meet which is not the in case of #define. #define is interpreted as compile time itself.
Here is the MSDN definition of typedef and #define
A typedef declaration introduces a name that, within its scope, becomes a synonym for the type given by the type-declaration portion of the declaration
When using DEFINE statements, all instances of that statement are replaced by the value of the statement during a preprocessing phase.
To convince your Boss
CHARPTR a, b
;After preprocessing, that line expands to
Here, only variable a is of type char * whereas b is simply char
If you use typedef
Here both a and b are both of type char *
不可以,在 C++ 中不鼓励使用预处理器宏 (
#define
)。使用typedef
代替:编辑:为了说服你的老板,你可以使用 Pardeep 发布的指针技巧,但使用引用引入一个微妙的错误会更
有趣:No, the use of preprocessor macros (
#define
) is discouraged in C++. Use atypedef
instead:Edit: to convince your boss, you can use the pointer trick Pardeep posted, but it's even more
funinstructive to introduce a subtle bug using references:#define 只是一个文本替换,它可能会导致一些问题,从而产生您不想要的代码。
typedef 是否为数据类型等提供别名的正确方法。
这是一个 #define 严重失败的例子!
#define is just an textual replace and it can lead a few problems, resulting in code that you dont intend to have.
typedef if the right way to give alias names for datatypes etc.
Heres an example where #define fails horribly!
不,对于定义类型别名,有一个更好的工具:
#define 导致文本替换,这可能会导致令人惊讶的结果。另一方面,
typedef
为其他类型创建适当的别名。No, for defining type aliases, there is a much better facility:
A
#define
results in a textual replacement, which can lead to surprising results.typedef
on the other hand creates a proper alias for some other type.不。在这种情况下最好使用
typedef
,如下所示:No. Its better to use a
typedef
in this case as: