2012-06-20 41 views
1

我正在從在線斯坦福大學課程學習面向對象的編程,有一部分我不確定有關聲明。我認爲你必須始終在頭文件中聲明原型,然後將代碼寫入實現文件中,但是教授在實現中在頭文件中沒有聲明原型的情況下編寫了一個方法,怎麼樣?在頭文件和實現中聲明方法原型

另外,有人可能請清除私人和公共之間的區別,如果沒有原型的方法是公共或私人的方法?沒有原型的方法不是來自超類。

回答

2

這是一種完全合法的方式來聲明不在類實現本身之外使用的方法。

編譯器會在實現文件中找到方法,只要它們在使用它們的方法之前。然而,情況並非總是如此,因爲新的LLVM編譯器允許以任何順序聲明方法並從給定文件引用方法。

有用於聲明一個實現文件中方法幾個不同的風格:

//In the Header File, MyClass.h 
@interface MyClass : NSObject 
@end 

//in the implementation file, MyClass.m 
//Method Decls inside a Private Category 
@interface MyClass (_Private) 
    - (void)doSomething; 
@end 

//As a class extension (new to LLVM compiler) 
@interface MyClass() 
    - (void)doSomething; 
@end 

@implementation MyClass 
//You can also simply implement a method with no formal "forward" declaration 
//in this case you must declare the method before you use it, unless you're using the 
//latest LLVM Compiler (See the WWDC Session on Modern Objective C) 
- (void)doSomething { 
} 

- (void)foo { 
    [self doSomething]; 
} 
@end 
2

如果你在頭文件中編寫方法,它是公共的,並且可以被其他類/對象訪問。如果你沒有在頭文件中聲明它,這個方法是一個私有方法,這意味着你可以在你的類的內部訪問它,但沒有其他類可以使用這個方法。

+0

當你downvote請這麼好心增加的一個原因。 – Pfitz