2014-10-12 208 views
-1

int main中聲明的所有變量在int pickword中不起作用。它只是說「variable not declared in this scope」。當我在int main之前聲明所有變量時,此問題消失。但我儘量避免使用全局變量,但靜態字沒有做任何事情變量未在範圍內聲明

#include <iostream> 
#include <cstdlib> 
#include <ctime> 
using namespace std; 
pickword(); 

int main() 
{ 
    static struct word 
    { 
     string indefSing; 
     string defSing; 
     string indefPlural; 
     string defPlural; 
    }; 
    static word aeble = {"aeble", "aeblet", "aebler", "aeblerne"}; 
    static word bog = {"bog", "bogen", "boger", "bogerne"}; 
    static word hund = {"hund", "hunden", "hunde", "hundene"}; 
    static string promptform; 
    static string wordform; 
    static word rightword; 

    void pickword(); 

    cout << "Decline the word " << rightword.indefSing << "in the " << promptform << endl; 

    return 0; 
} 

void pickword() 
{ 
    cout << "welcome to mr jiggys plural practice for danish" << endl; 

    pickword(); 
    using namespace std; 

    srand(time(0)); 
    int wordnumber = rand()% 3; 
    switch (wordnumber) //picks the word to change 
    { 
    case 0: 
     rightword = aeble; 
     break; 
    case 1: 
     rightword = bog; 
     break; 
    case 2: 
     rightword = hund; 
     break; 
    }; 

    int wordformnumber = rand()% 3; 
    switch (wordformnumber) //decides which form of the word to use 
    { 
    case 0: 
     wordform = rightword.defSing; 
     promptform = "definite singular"; 
    case 1: 
     wordform = rightword.indefPlural; 
     promptform = "indefinite plural"; 
    case 2: 
     wordform = rightword.defPlural; 
     promptform = "indefinite Plural"; 
    }; 
} 
+1

無關:pickword的'的無限遞歸()'是在製造一個火車事故。我希望你喜歡這個受歡迎的消息,因爲你即將看到一大堆*。 – WhozCraig 2014-10-12 07:21:58

回答

0

您需要將這些變量傳遞給pickword因爲主函數內聲明的所有變量不共享與pickword功能範圍。每個功能都有自己的範圍。所以你只能通過調用它來訪問在pickword函數中聲明在主函數中的變量。所以要麼在主函數之外聲明你的變量,以便它們可以被其他函數訪問,或者只是將它們作爲參數傳遞給你需要訪問它們的函數。

0

您已經在main(即局部變量)中聲明瞭一些變量。怎麼可能pickword知道這些局部變量。

這裏有兩個選項,這取決於您是否希望pickword改變在主OR中聲明的變量的狀態。

1)按價值傳遞。

int main() 
{ 
int x ; 
pickword (x); 
} 
pickword (int x); //Pickword can't change value of x. 

2)通過引用傳遞: -

int main() 
{ 
int x ; 
pickword (x); 
} 
pickword(int& x); //Pickword can change value of x.