物件導向 物件初始化

2021-07-09 11:08:13 字數 1338 閱讀 2540

[類名 alloc]

;

使用nsobject提供的init方法雖然可以完成初始化,但由於它只是完成最基本的初始化,因此物件的所有成員變數依然為0。

重寫init方法,可以加入任意的自定義處理**對屬性執行初始化

例:

在.h檔案中定義屬性

@property (nonatomic ,copy) nsstring * name;

@property (nonatomic ,assign) int age;

@property (nonatomic ,copy) nsstring * address;

在.m檔案中

//重寫init方法

- (id) init

return

self;

}

例:

在.h檔案中定義

@property (nonatomic , copy) nsstring * brand;

@property (nonatomic , copy) nsstring * model;

@property (nonatomic , copy) nsstring * color;

//定義乙個 initwithbrand:model:方法,完成自定義初始化

- (id) initwithbrand:(nsstring *) brand model:(nsstring *) model;

//定義乙個initwithbrand:model:color:方法,完成自定義初始化

- (id) initwithbrand:(nsstring *) brand model:(nsstring *) model color:(nsstring *) color;

在.m檔案中

//重寫init方法,完成自定義初始化

- (id) init

return

self;

}//實現initwithbeand:model:方法,完成自定義初始化

- (id) initwithbrand:(nsstring *) brand model:(nsstring *)model

}//實現initwithbeand:model:color:方法,完成自定義初始化

- (id) initwithbrand:(nsstring *) brand model:(nsstring *)model color:(nsstring *) color

return

self;

}

python物件導向 建立物件初始化 new

在python中,當使用類名 建立物件時,會自動執行以下操作 1 為物件在記憶體中分配空間 建立物件 new 2 為物件的屬性設定輸出值 初始化方法 init new 方法 使用類名建立物件,python的直譯器會首先呼叫 new 方法為物件分配儲存空間 new 方法時乙個由objct基類提供的內建...

物件導向(二)初始化方法

初始化方法 類名 就可以建立乙個物件 類名 建立物件的時候,python直譯器會自動執行以下操作 為物件在記憶體中分配空間 建立物件 呼叫初始化方法為物件的屬性設定初始值 這個初始化方法是內建方法,是專門用來定義乙個類據有哪些屬性和方法的 class cat def init self,name s...

C 物件導向 初始化列表

初始化列表是指在建構函式中,我們可以提前給建構函式進行初始化。傳統的初始化 person int a,int b,int c 初始化列表 person int a,int b,int c m a a m b b m c c 其實這兩個的區別不是很大,但是平常如果出現了這樣的 要看得懂 我們也可以修改...