2011-11-22 153 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);