未在作用域中声明变量
Variable was not declared in scope
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.
相关文章:
- 在疯狂的部分中声明变量
- 如何在C++中为高分辨率时钟声明变量?
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- CUDA 的性能取决于声明变量
- 如何在不为其声明变量的情况下获取和使用常量值的地址?
- C++声明变量时自动类型推断而不初始化
- 在不同循环中多次声明变量的优点
- 奇怪的错误 C2131 与 constexpr 声明变量
- 是否可以在 "if" 语句中声明变量?
- 在python-ctypes中声明变量并传递给dll函数
- 在递归函数C++中声明变量
- 只有一个定义/声明时标头声明变量的多堆定义错误
- 奇怪的未声明变量编译器错误
- 我在C++程序中声明变量时遇到问题
- 在命名空间中声明变量
- C++ lambda 按值捕获,而无需更早声明变量
- 声明变量以保存字符串列表时的内存分配
- 如何声明C 变量应突变
- 为什么允许在开关语句中声明变量?但不是声明 初始化
- 在同一命名空间中声明变量和函数是否出错?[C++]