【问题标题】:passing struct parameter by reference c++通过引用c ++传递结构参数
【发布时间】:2012-01-04 05:26:39
【问题描述】:

如何通过引用c++传递结构参数,请看下面的代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;
struct TEST
{
  char arr[20];
  int var;
};

void foo(char * arr){
 arr = "baby"; /* here need to set the test.char = "baby" */
}

int main () {
TEST test;
/* here need to pass specific struct parameters, not the entire struct */
foo(test.arr);
cout << test.arr <<endl;
}

所需的输出应该是婴儿。

【问题讨论】:

标签: c++ struct pass-by-reference


【解决方案1】:

我会在 c++ 中使用 std::string 而不是 c 数组 所以代码看起来像这样;

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>

using namespace std;
struct TEST
{
  std::string arr;
  int var;
};

void foo(std::string&  str){
  str = "baby"; /* here need to set the test.char = "baby" */
}

int main () {
  TEST test;
  /* here need to pass specific struct parameters, not the entire struct */
  foo(test.arr);
  cout << test.arr <<endl;
}

【讨论】:

  • +1 有时最好的答案就是忽略 OP 的初始尝试并使用正确的 C++。
  • 我认为这指向了 C++ 的最大问题(至少对于初学者而言):该语言允许各种垃圾,并且不强制执行“正确的 C++”。
【解决方案2】:

这不是您想要分配给 arr 的方式。 它是一个字符缓冲区,所以你应该将字符复制到它:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;
struct TEST
{
  char arr[20];
  int var;
};

void foo(char * arr){
  strncpy(arr, "Goodbye,", 8);
}

int main ()
{
  TEST test;
  strcpy(test.arr, "Hello,   world");
  cout << "before: " << test.arr << endl;
  foo(test.arr);
  cout << "after: " << test.arr << endl;
}

http://codepad.org/2Sswt55g

【讨论】:

    【解决方案3】:

    看起来您正在使用 C 字符串。在 C++ 中,您可能应该考虑使用 std::string。在任何情况下,这个例子都传递了一个char 数组。因此,为了设置婴儿,您需要一次一个字符(不要忘记 C 字符串末尾的 \0)或查看 strncpy()

    所以不要尝试arr = "baby" strncpy(arr, "baby", strlen("baby"))

    【讨论】:

      【解决方案4】:

      由于上述原因,它对您不起作用,但您可以通过在类型右侧添加 & 作为参考。即使我们纠正他,至少我们应该回答这个问题。而且它对你不起作用,因为数组被隐式转换为指针,但它们是 r 值,不能转换为引用。

      void foo(char * & arr);
      

      【讨论】:

        猜你喜欢
        • 2013-05-12
        • 2011-02-02
        • 1970-01-01
        • 1970-01-01
        • 2018-09-22
        • 2015-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多