obj-c 中的参数通过引用传递

发布于 2024-11-04 08:34:33 字数 402 浏览 1 评论 0原文

我刚刚做了一项研究,但我遇到了一个问题

- (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 类型冲突;这是正确的做法吗?谢谢!

I just did one research, but I am having a problem

- (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);
}

I am getting conflicting type of swap; is this correct way of doing this? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半衾梦 2024-11-11 08:34:33

如果您希望交换 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

If you want r1 and r2 to be swapped, you either have to pass pointers, or use C++ references. Note that using C++ references will require you to dive into Objective-C++, which in this case means naming your file .mm instead of .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;
}

Then, use one of your implementations like so:

- (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;
}

The output, either way:

x = 4, y = 3

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文