Unlike C ++, object-C does not stipulate that a constructor and destructor must be implemented. Therefore, in object-C, in fact, there is no such concept as constructor and destructor. Instead, it should be the creation and initialization of objects and the release of objects. In object-C, calling alloc/init is actually to create and initialize an object. Alternatively, you can write a function by yourself, as long as the data member initialization of the class is completed, and return the pointer (Self) of this instance. Example:
1. Code:
Add the following code to "2. Create a simple class (Object-C)" in this series of instances:
// Fraction. h
-(Fraction *) initwithnumerator: (INT) n denominator: (INT) D;
-(Fraction *) Init: (INT) n denominator: (INT) D;
-(Void) setnumerator: (INT) n anddenominator: (INT) D;
// Fraction. m
-(Fraction *) initwithnumerator: (INT) n denominator: (INT) d {
Self = [Super init];
If (Self ){
[Self setnumerator: N anddenominator: d];
}
Return self;
}
-(Fraction *) Init: (INT) n denominator: (INT) d {
Self = [Super init];
If (Self ){
[Self setnumerator: N anddenominator: d];
}
Return self;
}
-(Void) setnumerator: (INT) n anddenominator: (INT) d {
Numerator = N;
Denominator = D;
}
// Main. m
# Import <stdio. h>
# Import "fraction. H"
Int main (INT argc, const char * argv []) {
// Create a new instance
Fraction * frac = [[fraction alloc] init];
Fraction * frac2 = [[fraction alloc] init];
Fraction * frac3 = [[fraction alloc] initwithnumerator: 1 denominator: 3];
Fraction * frac4 = [[fraction alloc] init: 1 denominator: 4];
// Set the values
[Frac setnumerator: 1];
[Frac setdenominator: 1];
// Combined set
[Frac2 setnumerator: 1 anddenominator: 2];
// Print it
Printf ("the fraction is :");
[Frac print];
Printf ("\ n ");
Printf ("fraction 2 is :");
[Frac2 print];
Printf ("\ n ");
Printf ("fraction 3 is :");
[Frac3 print];
Printf ("\ n ");
Printf ("fraction 4 is :");
[Frac4 print];
Printf ("\ n ");
// Free memory
[Frac release];
[Frac2 release];
[Frac3 release];
[Frac4 release];
Return 0;
}
2. Compile:Example 2.
3. Description:
(1 ). both initwithnumerator and init can be considered as fraction constructor, but init is implemented by rewriting the parent class (nsobject). initwithnumerator can be considered as a common function, but the fraction Initialization is completed, so it can also be considered as a constructor. In object-C, constructor like C ++ or Java must have the same name as the class name.
(2) When implementing code, you must first call the init of the parent class, then initialize your own data members, and return self.
(3). In fact, the return value of the init function should be defined as ID.