2015-02-11 226 views
-2

有人可以請解釋如何將一個函數中的變量的值帶入另一個函數。我知道,只要函數結束,函數中的變量值就會被清除。但我怎麼告訴它不要這樣做。如何將變量的值從一個函數帶到另一個函數?

我正在嘗試將候選函數中的int ppl;值帶入投票函數。但是,正如你所看到的,它不會自己做。

void candidates() 
{   
    int ppl; 
    cout << "Hello please how many candidates are there?: "; 
    std::cin >> ppl; 
    string *cans = new string[ppl]; 
    for (int i = 0; i < ppl; i++) 
    { 
     cout << "Please type in the last name of candidate number: " << i + 1 << endl; 
     cin >> cans[i];cout << endl << endl; 
    } 

    for (int a = 0; a < ppl; a++) 
    { 
     cout << cans[a] << endl << endl; 
    } 
} 

void votes() 
{    
    int *vote = new int[ppl]; 

    // ... 
} 
+0

查看返回值和參考變量。 [在你學習的時候,這個網站應該會有很多幫助!](http://www.learncpp.com/) – Conduit 2015-02-11 21:09:13

+1

你應該看看如何將**參數**傳遞給函數並使用**返回**值。 – CoryKramer 2015-02-11 21:09:15

+0

'void candidates(int&ppl)'和'void votes(int const ppl)' – 101010 2015-02-11 21:10:49

回答

0

使用return

int candidates() 
{ 
    int ppl; 
    std::cin >> ppl; 
    ... 
    return ppl; 
} 

功能考生()現在收到的int所以現在你可以這樣做:

void votes() 
{ 
    int *vote = new int[candidates()]; 
} 

您也可以使用全局變量,或將變量傳遞ppl作爲int&以功能candidates()作爲參數,所以必須創建ppl (在主函數中),因此它可用於您需要的每個功能。

1

你想要的模式可能是:

std::vector<string> gather_data() {...} 

void use_data(std::vector<string> data) { ... } 

然後你就可以這樣做:

auto data = gather_data(); 
use_data(data); 

這將是更好的做法,以確保use_data不能修改其參數,並這個參數是通過引用傳遞的。所以:

void use_data(const std::vector<string>& data) { ... } 

更高級的模式是使用一類:

class Foo { 
    std::vector<string> data; 
public: 
    void gather() {...} 
    void use() {...} 
} 

Foo myFoo; 
myFoo.gather(); 
myFoo.use(); 

在這種情況下,你可以看到Foo的實例方法可以訪問其data

你當然不希望在沒有很好理由的情況下使用全局變量。

但是,如果您在此基礎級別提出問題,這意味着您需要read a book

你會發現僅僅通過提問就可以嘗試學習最難的語言之一是不切實際的。每個答案都會再提出10個問題。

+0

爲什麼你會用指針指向'string'的指針呢? – juanchopanza 2015-02-11 21:35:29

+0

@juanchopanza:固定。我試圖解決的主要問題是,無論答案是什麼,它都沒有什麼價值。還有一個比「不理解參數」*更直接的問題,即*「缺乏有組織的學習方法」*。 – 2015-02-11 21:40:03

相關問題