2012-06-20 44 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