2014-06-10 17 views
2

這是C++ Primer 5th的練習。我不知道如何解決它?如何返回對十個字符串數組的引用

問題描述爲:

編寫聲明返回到十成一個字符串數組的引用,而無需使用一個尾隨回報,decltype,和或一個類型別名的功能。

我的代碼:

#include <iostream> 
#include <string> 

std::string (&func(std::string a[])) [10] 
{ 
    return a; 
} 

int main() 
{ 
    std::string a[10]; 
    std::string (&b)[10] = func(a); 
    for (const auto &c : b) 
     std::cout << c << std::endl; 
    return 0; 
} 

編譯錯誤:

e6_36.cc:6:12: error: non-const lvalue reference to type 'std::string [10]' cannot bind to a value of unrelated type 'std::string *' (aka 'basic_string, allocator > *')

return a;

 ^

1 error generated.

+0

你檢查出[這個答案](http://stackoverflow.com/a/5399014/1214731)? – tmpearce

+1

你已經得到了正確的返回類型。只是您返回的值不是正確的類型,因爲您的參數類型是錯誤的。 –

+0

要清楚:問題只是要求'std :: string(&func())[10];'。這是一個函數聲明。你試圖進一步提供一個函數定義並給出一些參數,這就是你遇到一些麻煩的地方。 –

回答

1

您可以通過引用傳遞數組,這樣你就可以退貨:

std::string (&func(std::string (& a) [10])) [10] 
{ 
    return a; 
} 

或者讓事情更清晰,請爲您的字符串數組使用typedef

typedef std::string StrArray[10]; 

StrArray& func2(StrArray& a) { 
    return a; 
} 

編輯:

當你確實:

std::string (&func(std::string a[])) [10] 
{ 
    return a; // error ! 
} 

的參數astd::string陣列和衰減到指針std::string*,這是由值來傳遞(因此,複製):你要求編譯器將一個非const引用(返回類型)綁定到一個臨時的,這在C++中是非法的。

+0

你的回答是對的,但我不明白爲什麼要在參數中使用參考。是否因爲如果我不使用引用,我會返回對本地** **的副本的引用? – Aristotle0

+0

@ Aristotle0:請參閱我的編輯 – quantdev

+0

在錯誤的代碼中,問題是試圖將'std :: string(&)[10]'綁定到'std :: string *',這是一種類型不匹配。即使使用了一個const引用,它也會因爲同樣的原因而失敗。 –

0

串(& FUNC(串(&如)[10]))[10]

  • 串(&如)[10]是10個類型元件的陣列的引用。 (字符串(& as)[10])表示我們可以調用func,其參數是對10個字符串類型元素的數組的引用。
  • (& func(string(& as)[10]))表示引用是return。
  • (& FUNC(串(&如)[10]))[10]表示,參考產生尺寸的陣列10
  • 串(& FUNC(串(&如)[10]))[10 ]表示數組中的元素類型是字符串類型。
#include <iostream>  
#include <string>  

std::string (&func(std::string(&as)[10]))[10]  
{ 
    for (int i = 0; i != 10; ++i) { 
     as[i] = as[i] + " number " + std::to_string(i); //append to string 
    } 
    return as; 
} 

int main() 
{ 
    std::string array_str[10]; 
    // initialize array with "I am" 
    for (auto &str : array_str) { 
     str = "I am"; 
    } 
    // give reference of string[10] to func 
    using aStr = std::string[10]; // alias 
    aStr &ref_aStr = func(array_str); 
    // print to see results 
    for (auto str : ref_aStr) { 
     std::cout << str << std::endl; 
    } 
    return 0; 
} 
相關問題