【问题标题】:Instantiating new object within switch block - why does it fail?在 switch 块中实例化新对象 - 为什么会失败?
【发布时间】:2008-12-14 02:06:47
【问题描述】:

为什么

switch ([document currentTool]) {
    case DrawLine:
        NSBezierPath * testPath = [[NSBezierPath alloc]init];
        //...rest of code that uses testPath....

结果

error:syntax error before "*" token

测试路径?

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    你不能在 case 语句中实例化一个对象,除非你把它放在一个新的范围内。这是因为否则你可以这样做:

    switch( ... ) {
        case A:
           MyClass obj( constructor stuff );
           // more stuff
           // fall through to next case
        case B:
           // what is the value of obj here? The constructor was never called
        ...
    }
    

    如果您希望对象在案件期间持续存在,您可以这样做:

    switch( ... ) {
        case A: {
           MyClass obj( constructor stuff );
           // more stuff
           // fall through to next case
        }
        case B:
           // obj does not exist here
        ...
    }
    

    这在 Objective C 以及 C 和 C++ 中都是一样的。

    【讨论】:

      猜你喜欢
      • 2011-03-26
      • 1970-01-01
      • 2021-02-17
      • 2018-11-11
      • 1970-01-01
      • 2019-12-10
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多