C语言中在函数定义时,函数名后面括号里的参数称为形式参数,简称形参。
在调用该函数时,函数名口号中的参数称为实际参数,简称实参。
那么实参和形参的区别是什么?
函数在没有被调用的时候,括号里的形参,并没有分配内存单元。而当函数被调用的时候,形参分配内存单元,实参将其值赋值给形参,这称之为函数参数的传递。
注意:形参分配的内存单元和实参是不相干的,形参分配内存单元时与实参是独立的内存单元,但是实参和形参内寸单元里的值是一样的。
这样就好理解当一个函数的参数是指针型时,在函数中改变对象的成员变量时,原对象成员变量是否改变问题。
源代码如下:
@import <Foundation/Foundation.h>
@interface Person :NSObject
{
@public
int age;
double weight;
}
-(void)run;
@end
@implementation Person
-(void)run
{
NSLog(@"the person is %d age and %f kg weigth!,age,weight");
}
@end
void test1(Person *newperson)
{
newperson->age=23;
newperson->weight=63.0;
}
void test2(Person *newperson)
{
Person *person2=[Person new];
person2->age=22;
person2->weight=62.0;
newsperson=person2;
}
void test3(int age,double weight)
{
age=25;
weight=65.0;
}
int main()
{
Person *person1=[Person new];
person1->age=22;
person1->weight=62.0;
[person1 run];
test1(person1);//调用函数test1
[person1 run];
test2(person1);//调用函数test2
[person1 run];
test3(person1->age,person1->weight);//调用函数test3
[person1 run];
return 0;
}
结果输出:
the person is 22 age and 62.0 kg weigth! //
the person is 23 age and 63.0 kg weigth!//调用test1后的输出
the person is 23 age and 63.0 kg weigth!//调用test2后的输出
the person is 23 age and 63.0 kg weigth!//调用test3后的输出
当调用text1时:形参被调用时分配内存单元,内存单元里存储值和实参传递的值一样。则形参为指针时,被实参传值后,形参内存单元里存储的地址与实参一样,即指向同一块内存单元,本例中都指向person1对象。text1中的newperson->age=23;newperson->weight=63.0;执行后,person1指向对象的成员变量改变为23,63.0.
当调用text2时,形参内存单元里存储的地址与实参一样,都指向person1对象。但是text2中新建了一个对象person2,并且赋值成员变量age=22,age=63.0.然后执行newsperson=person2;使形参存储的地址指向了新对象person2。但实参person1却没有发生变化,仍然指向原有对象。所以仍输出the person is 23 age and 63.0 kg weigth!
掉用text3时,同理调用text2,只不过是形参的数值发生了变化并没有影响实参。所以输出仍为he person is 23 age and 63.0 kg weigth!
/****************************************分割线**********************************/
OC中方法与函数的区别
方法:
1.方法的实现只能写在类的实现里,方法的声明只能写在类的声明里。
2.对象方法都是以(-)减号开头的。
3.对象方法只能由对象调用
函数:
1.函数属于整个文件,除了@interface和@end之间,函数可以写在任何地方。
2.函数调用不依赖对象。
3.函数不能直接访问类的成员变量。