在switch块中实例化新对象 - 为什么会失败?

Joe*_*Joe 4 objective-c

为什么

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

造成

error:syntax error before "*" token

对于testPath?

Gra*_*row 10

除非将其放在新范围内,否则无法在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
    ...
}
Run Code Online (Sandbox Code Playgroud)

如果希望对象在案例持续时间内持续,则可以执行以下操作:

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

在Objective C以及C和C++中也是如此.