使用“typedef”或“使用”定义一个结构 - 哪个最好?
示例结构:
typedef struct tagExportSettings
{
COLORREF crHeading{};
COLORREF crEvenBack{};
COLORREF crOddBack{};
COLORREF crHighlight{};
COLORREF crDate{};
COLORREF crEvent{};
COLORREF crEmpty{};
COLORREF crNotes{};
} EXPORT_SETTINGS_S;
视觉辅助说:
typedef
可以转换为using
声明。
更改此代码有什么真正的好处吗?
我在软件中的所有代码都使用 EXPORT_SETTINGS_S
所以我不想破坏该语法。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更好的是两者都不使用。一种类型名称就足够了。选择
tagExportSettings
或EXPORT_SETTINGS_S
并坚持下去。例子:正如我所说,选择任一名称。如果您使用
EXPORT_SETTINGS_S
,则将该类命名为EXPORT_SETTINGS_S
:如果某些内容仍然引用
tagExportSettings
,则重构代码以使用规范名称。但更一般而言,
using
优于typedef
,因为它更具可读性。至少有两个原因:使用
typedef
语法,哪个是旧名称、哪个是新别名并不直观:使用
通过熟悉的初始化模式变得直观:typedef
语法对于程序员来说很难解析复合名称,因为别名是“交错的”:Even better is to use neither. One type name should be enough. Pick either
tagExportSettings
orEXPORT_SETTINGS_S
and stick with it. Example:As I said, pick either name. If you use
EXPORT_SETTINGS_S
, then name the class asEXPORT_SETTINGS_S
:If something still refers to
tagExportSettings
, then refactor the code to use the canonical name.But more generally,
using
is preferred totypedef
because it's more readable. There are at least two reasons for it:With
typedef
syntax it isn't intuitive which is the old name and which is the new alias:using
is intuitive through familiar pattern of initialisation:typedef
syntax is difficult for a programmer to parse in case of compound names because the alias is "interleaved":如果您使用 C++ 编写,
using
会更好。例如,像这样的模板结构:您可以像这样使用
typedef
或using
:但如果使用模板,则只有
using
可以工作:If you are writing in C++,
using
is much better. For example, a template struct like this:You can use
typedef
orusing
like this:But only
using
can work if use template:假设是纯 C++,这取决于您是否使用原始指针。如果不这样做,则只需使用正确的名称定义结构,而不使用
typedef
或using
。如果您在 Windows 中经常使用原始指针,那么习惯上不仅定义别名,还定义指针类型:
只有当您习惯
LPXXX
“类型”。如果你是一个*
人,那么就没有必要。这些都不是
使用
的明确案例。Assuming pure C++, it depends if you're using raw pointers or not. If you don't, then just define the struct under proper name without either
typedef
orusing
.If you're using raw pointers a lot and in Windows, it's customary to define not just alias but a pointer type as well:
That certainly matters only if you are accustomed to
LPXXX
"types". If you're a*
person, then there's no need.Neither of those are a clear-cut case for
using
.