在C ++ / CLI中通过引用传递参数,因此重新分配会影响调用者 [英] Pass an argument by reference in C++/CLI so re-assignment affects the caller

查看:141
本文介绍了在C ++ / CLI中通过引用传递参数,因此重新分配会影响调用者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能不是一个困难的问题,但我总是有点困惑,如何处理String类型作为Visual C ++中的参数。我有以下函数:

Probably this is not a difficult question, but I am always a little bit confused on how to treat String type as an argument in Visual C++. I have the following to functions:

void function_1(String ^str_1)
{
  str_1 = gcnew String("Test");
}

void function_2()
{
  String ^str_2 = nullptr;
  function_1(str_2);
}

调用 function_1 str_2 仍然等于 null ,但我想实现的是 str_2 等于 Test 。那么,如何实现 str_1 的内容传递给 function_2

After calling function_1, str_2 is still equal to null, but what I want to achieve is that str_2 is equal to Test. So, how can I achieve that the content of str_1 is passed to function_2?

感谢您的任何建议。

推荐答案

使用跟踪参考

void function_1(String ^%str_1)
{
  str_1 = gcnew String("Test");
}

说明:传递 String ^ 就像传递一个指针一样。仅对引用的本地副本进行更改。 String ^%就像传递一个引用一样,就像你在调用一个应该改变原始指针的函数时传递一个指针一样。

Explanation: Passing String ^ is like passing a pointer. Changes are only made to the local copy of the reference. String ^% is like passing a reference to a reference... just as you would pass a pointer to a pointer when calling a function that should change the original pointer.

这篇关于在C ++ / CLI中通过引用传递参数,因此重新分配会影响调用者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆