未在此范围内声明错误 'settings'

Error 'settings' was not declared in this scope

本文关键字:settings 错误 声明 范围内      更新时间:2023-10-16

首先,这是我第一次写代码,所以我是个新手。

我是用devkit pro写的,所以它都是用c++写的。我想有一个菜单,每个菜单屏幕是一个空白,我需要有一种方法可以回到上一个菜单。

另外,我确保在实际的代码中没有语法错误(除非没有在此范围内声明被认为是语法错误)。

如何做到这一点,而不得到"错误'设置'未在此范围内声明"。代码:

    //Headers go here
    void controls()
    {
                                 //Inits and what not go here
            if (key_press & key_down) 
    /*This is generally how you say if the down key has been pressed (This syntax might be wrong, but ignore that part)*/
            {
            settings(); //This part doesn't work because it can't read back in the code
            }
    }
    void settings()
    {
                                 //Inits and what not go here
            if (key_press & key_down) 
            {
            controls();
            }
    }
    void mainMenu()
    {
                 //Inits and what not go here
            if (key_press & key_down) 
            {
                    settings();
            }
    }

并且注意,在这段代码之外的某个地方,mainMenu()将被激活。有人知道怎么正确编码吗?

在函数调用的那一刻,编译器对这个函数一无所知。有两种方法可以让编译器意识到你的函数:声明定义

要声明函数,必须将函数摘要(函数参数和返回值)像这样放在编译模块的顶部。

void settings(void);

要解决这个问题,你应该在第一次调用settings()函数之前声明它。

在您的情况下,您可能应该在文件的顶部声明函数。通过这种方式,编译器将知道函数和应该传递的参数。

void settings();
void controls()
{
...
}
void settings()
{
...
}
void mainMenu()
{
...
}

很好的文章开始,并获得一些额外的细节:声明和定义在msdn

快速解决方案是在controls()之前添加settings()的前向声明,如下所示:

void settings() ;

完整代码:

//Headers go here
void settings() ;
void controls()
{
                             //Inits and what not go here
        if (key_press & key_down) 
/*This is generally how you say if the down key has been pressed (This syntax might be wrong, but ignore that part)*/
        {
        settings(); //This part doesn't work because it can't read back in the code
        }
}
void settings()
{
                             //Inits and what not go here
        if (key_press & key_down) 
        {
        controls();
        }
}
void mainMenu()
{
             //Inits and what not go here
        if (key_press & key_down) 
        {
                settings();
        }
}

参见前面的线程c++ -前向声明

settings()为局部函数。只能在定义之后调用。移动controls()以上的定义或使其通过头文件可用。

问题是settings()是在controls()之后声明的,而controls试图调用settings()。但是,由于settings()还不存在,它无法这样做。

您可以将settings()的定义移动到controls()之前,或者您可以在controls()之前对settings()进行前向声明。

void settings(); //forward declaration
void controls() { 
  .....
}
void settings() {
  .... 
}

您是否先在头文件中声明了settings() ?此外,我没有看到你的任何方法范围到你的类名或名称空间,如果你可能会如果这些方法在头文件中声明。

如果你不需要头文件,不管什么原因,然后改变你写的顺序。在使用settings()之前定义它