2013-02-23 52 views
0

我正在做Person和PersonChild類的示例。 我想知道爲什麼我可以從Person類中獲得這個Int。繼承Xcode中的其他類

//主

#import <Foundation/Foundation.h> 
#import "Person.h" 
#import "PersonChild.h" 

int main(int argc, const char * argv[]){ 
    @autoreleasepool { 
     PersonChild *Ben = [[PersonChild alloc]init]; 
     Ben.age = 25; <-- Property 'age' not found on object of type 'PersonChild *' 
     [Ben printThing]; 
    } 
    return 0; 
} 

// Person類

#import "Person.h" 

@implementation Person 
@synthesize age, weight; 

@end 

//Person.h

#import <Foundation/Foundation.h> 

@interface Person : NSObject{ 
    int age; 
} 
@property int age, weight; 
@end 

// PersonChild類

#import "PersonChild.h" 

@implementation PersonChild 

-(void) printThing{ 
    NSLog(@"%i", age); 
} 
@end 

//PersonChild.h

#import <Foundation/Foundation.h> 
#import "Person.h" 

@class Person; 
@interface PersonChild : NSObject 

-(void) printThing; 

@end 

回答

3

PersonChild是不會由人繼承。 PersonChild.h的正確語法是:

#import "Person.h" 
@interface PersonChild : Person 
+0

謝謝!我以爲我嘗試過......我知道這是一件小事...... – DDukesterman 2013-02-23 20:41:05

0

除非你已經列出了您的標題不正確,「年齡」是person.h的屬性,而「本」是personChild.h

的實例變量的一個實例(iVar)必須在該類(或超類)中聲明爲實例變量。

我認爲你混淆了繼承和導入。您在上面做的是將Person.h導入到PersonChild.h中,並假設這將導致所有「Person」類iVars在「PersonChild」類中可用。

瞭解差異的一種方法是將PersonChild.h更改爲以下內容。請注意,如何在@interface行上添加Person是正確的方式,以表示PersonChild類從Person類繼承。這應該修復你的錯誤。

#import <Foundation/Foundation.h> 
#import Person.h  

@interface PersonChild : Person 

-(void) printThing; 
@end 

希望這有助於