未在作用域中声明变量

Variable was not declared in scope

本文关键字:声明 变量 作用域      更新时间:2023-10-16

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

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

您已经在main中声明了一些变量(即局部变量)。pickword怎么会知道这些局部变量呢。

这里有两个选项,这取决于您是否希望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.