相关疑难解决方法(0)

"static const"vs"#define"vs"enum"

在C中的以下陈述中哪一个更好用?

static const int var = 5;
Run Code Online (Sandbox Code Playgroud)

要么

#define var 5
Run Code Online (Sandbox Code Playgroud)

要么

enum { var = 5 };
Run Code Online (Sandbox Code Playgroud)

c constants

550
推荐指数
12
解决办法
33万
查看次数

enum vs static consts

我目前正在考虑是否更喜欢名称空间枚举或命名空间的静态组的问题.什么应该是默认选择,为什么?

选项1:

namespace Direction
{
    enum Direction
    {
        north,
        east,
        south,
        west,
    };
}
Run Code Online (Sandbox Code Playgroud)

选项2:

namespace Direction
{
    static const unsigned char north = 0;
    static const unsigned char east = 1;
    static const unsigned char south = 2;
    static const unsigned char west = 3;
}
Run Code Online (Sandbox Code Playgroud)

两者都有其优点和缺点.

专业版:

  1. 一些类型的安全:

    void foo(Direction dir); // the compiler won't allow you to just pass an int or a value of an unrelated enum without explicitly casting it
    
    Run Code Online (Sandbox Code Playgroud)

Contra enum:

  1. 类型安全性相当有限:

    enum A …
    Run Code Online (Sandbox Code Playgroud)

c++ enums c++03

12
推荐指数
1
解决办法
4415
查看次数

标签 统计

c ×1

c++ ×1

c++03 ×1

constants ×1

enums ×1