2014-10-12 150 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.