【问题标题】:c++ structs and constC++ 结构和常量
【发布时间】:2010-08-17 07:52:08
【问题描述】:

好吧,我有结构

struct balls {
    balls(UINT_PTR const &val) : BALL_ID(val){}
    int Ex;
    int Ey;
    const UINT_PTR BALL_ID;
};
balls ball1(0x1);

我有一个 switch 语句

switch(wParam)
        {
        case ball1.BALL_ID:
                if(ball1.Ex<300)
                {
                    ball1.Ex++;
                }
                else
                {
                    KillTimer(hWnd, ball1.BALL_ID);
                }
                InvalidateRect(hWnd, rect, false);
                break;
        case SCORECOUNTER_ID:
                if(life==0)
                {
                    if(scorecounter<1000)
                    {
                        scorecounter+=100;
                        _swprintf(str, _T("Score: %d"), scorecounter);
                        InvalidateRect(hWnd, rect, false);
                    }
                    else
                    {
                        _swprintf(level, _T("Level: %d"), 2);
                        InvalidateRect(hWnd, rect, false);
                    }
                }
            break;
        }

我得到一个错误,ball1.BALL_ID is not constant 第二行应该解决这个问题,但它不知道?

【问题讨论】:

    标签: c++ visual-c++ winapi struct


    【解决方案1】:

    case 标签必须是整型常量表达式——它们必须在翻译期间(即编译时)是可评估的。在这种情况下,BALL_ID 无法在编译时评估。不同的ball 对象被允许有不同的BALL_ID 值,因此编译器不可能在翻译过程中对其进行评估。此外,.(对象的成员解析运算符)不能在 case 标签中使用(即,即使您确实使 BALL_ID static 对您不起作用)。

    我会冒险猜测SCORECOUNTER_ID 是一个宏/static const int,因此可以由编译器评估。

    您可以使用命名空间范围 enumint 来解决此问题。例如:

    struct s {
     s(const int t) : x(t) {}
     const int x;
    };
    
    namespace s2 {
     const int val = 42;
    }
    
    int main() {
     s ss(4);
     int val = 42;
     switch (val) {
      case s2::val:
      break;
      }
    }
    

    【讨论】:

    • ...为什么是的,当然,除非 OP 需要坚持 switch!
    【解决方案2】:

    必须在编译时知道案例标签(基本假设是,switch 的实现比在编译时知道值的 if 序列更有效,例如使用跳转表)。 const 是必需的,但还不够。 ball.BALL_ID 是 const 在编译时未知的东西,所以不能是 case 标签。

    【讨论】:

      【解决方案3】:

      并非所有整数类型的常量变量都是常量表达式。 switch 语句的 case 标签需要一个常量表达式。

      【讨论】:

        猜你喜欢
        • 2012-10-16
        • 1970-01-01
        • 1970-01-01
        • 2012-08-18
        • 1970-01-01
        • 2011-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多