我刚做了一项研究,但我遇到了问题
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
int r1=40,r2=5;
swap(r1,r2);
NSLog(@" temp is %d",r1);
}
void swap(int r1, int r2)
{
NSLog(@" m i 1st");
int temp;
temp=r1;
r1=r2;
r2=temp;
NSLog(@" temp is %d",r1);
}
我遇到了swap
的冲突类型;这是正确的做法吗?谢谢!
答案 0 :(得分:2)
如果要交换r1
和r2
,则必须传递指针或使用C ++引用。请注意,使用C ++引用需要您深入了解Objective-C ++,在这种情况下,这意味着命名文件.mm
而不是.m
。
void swap_with_pointers(int *r1, int *r2)
{
int temp;
temp = *r1;
*r1 = *r2;
*r2 = temp;
}
void swap_with_references(int &r1, int &r2)
{
int temp;
temp = r1;
r1 = r2
r2 = temp;
}
然后,使用您的一个实现:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
int x = 3;
int y = 4;
swap_with_pointer(&x, &y); // swap_with_references(x,y);
printf("x = %d, y = %d", x, y);
return 0;
}
输出,无论如何:
x = 4,y = 3