2011-11-22 154 views
1

如何通过引用C++传递结构参数,请参阅下面的代码。通过引用传递结构参数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; 
} 

希望的输出应该是宝贝。

+2

看起来您正在学习C +'',并被告知您正在学习C++。我会推荐[一本很好的C++入门书](http://stackoverflow.com/q/388242/46642)。 –

回答

1

这不是你想要分配给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

1

看起来你正在使用C字符串。在C++中,您应该考虑使用std::string。无论如何,这个例子都通过了一个char数组。因此,为了设置宝宝,您需要一次完成一个字符(不要忘记\0最后为C字符串),或者查看strncpy()

因此,而不是arr = "baby"尝试strncpy(arr, "baby", strlen("baby"))

5

我将会用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; 
} 
+7

+1有时候最好的答案只能忽略OP的初始尝试并使用正确的C++。 –

+2

我认为用C++指出了最大的问题(至少对于初学者):该语言允许各种垃圾,并且不强制实施“正确的C++”。 – Walter

1

它不会为你工作beause以上原因,但你可以通过添加&的类型的右路传中作为参考。即使我们纠正他,至少我们应该回答这个问题。它不适合你,因为数组隐式转换为指针,但它们是r值,不能转换为引用。

void foo(char * & arr);