变量未在范围内声明

时间:2014-10-12 07:16:58

标签: c++

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";
    };
}

2 个答案:

答案 0 :(得分:0)

您需要将这些变量传递给pickword,因为在main函数内声明的所有变量都不与pickword函数共享范围。每个函数都有自己的范围。所以你只能通过调用它来访问pickword函数中的main函数中声明的变量。因此,要么将变量声明在main函数之外,以便它们可以被其他函数访问,或者只是将它们作为参数传递给您需要访问它们的函数。

答案 1 :(得分:0)

您已在main中声明了一些变量(即局部变量)。怎么可能知道这些地方变种。

这里有两个选项,具体取决于您是否希望pickword更改在main中声明的变量的状态。

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.