2015-11-03 144 views
0

嗨我想學習目標C中的Opps概念,但我知道PHP,所以我採取了公共,私人和保護提到的波紋管程序。公共私人和保護在objective-c

<?php 


//Public properties and method can be inherited and can be accessed outside the class. 
//private properties and method can not be inherited and can not be accessed outside the class. 
//protected properties and method can be inherited but can not be accessed outside the class. 

class one 
{ 
    var $a=20; 
    private $b=30; 
    protected $c=40; 
} 

class two extends one 
{ 

    function disp() 
    { 
     print $this->c; 
     echo "<br>"; 
    } 
} 

$obj2=new two; 
$obj2->disp(); //Inheritance 
echo"<br>"; 

$obj1=new one; 
print $obj1->c; //Outside the class 

?> 

因此,我試圖在下面提到的Objective C代碼中進行轉換。

#import <Foundation/Foundation.h> 
@interface one : NSObject 
{ 
@private int a; 
@public int b; 
@protected int c; 
} 
@property int a; 
@property int b; 
@property int c; 

@end 
@implementation one 
@synthesize a,b,c; 
int a=10; 
int b=20; 
int c=30; 
@end 

@interface two : one 

-(void)setlocation; 

@end 

@implementation two 

-(void)setlocation; 
{ 
    // NSLog(@"%d",a); 
    NSLog(@"%d",b); 
    // NSLog(@"%d",c); 
} 

@end 
int main(int argc, const char * argv[]) { 
    @autoreleasepool { 
     // insert code here... 
     two *newtwo; 
     newtwo =[[two alloc]init]; 
     //calling function 
     [newtwo setlocation];  
    } 
    return 0; 
} 

當我運行上面的代碼我得到

2015-11-03 23:20:16.877 Access Specifier[3562:303] 0 

有人能解決我的問題。

+0

你正在編譯iOS或OS X嗎? –

+0

我正在編譯OS X命令行工具。只是想知道公共私人和受保護的概念。 – VyTcdc

回答

1

這種類型的問題之前,已要求並有在接受答案的Private ivar in @interface or @implementation

一般一個很好的解釋,我會建議你避免實例變量和使用@property代替。屬性具有隻讀/寫入控制的優點,以及免費的合成設置器和獲取器(如果您正在學習OOP概念是您應該採用的關鍵概念)。

屬性在Obj-C文件的@interface部分中聲明。對於訪問控制(根據鏈接),您沒有公共/私人/受保護的關鍵字。如果在.h文件中定義的所有Obj-C方法(以及擴展屬性)都是公共的。如果你想讓他們「私人」,你可以在.m文件中使用類別類別定義它們:

//MyClass.m 
@interface MyClass() 
@property(nonatomic, retain) NSString* myString; 
@end 

@implementation MyClass 
@end 
+0

首先感謝您對我的查詢的回覆,好吧,我想要得到的輸出值是30,但我在該編碼中得到0,您能否告訴我該怎麼做。 – VyTcdc

+0

如果您將您的ivars轉換爲屬性,則它們具有默認值。 'int'默認爲0,所以你需要在你的類被分配和初始化之後覆蓋你的'init'構造函數來設置這些值。 Obj-C自定義/覆蓋init的堆棧溢出搜索,或者參考最近的Obj-C書籍或學習網站的細微差別,因爲Obj-C的構造函數實現與PHP的不同。 –

+0

如果您還有其他人在StackOverflow上沒有詢問過的問題,請隨時發起一個新問題。 –