3

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

我正在使用 devkit pro 为 nds 写作,所以它都是用 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() 会被激活。那么有人知道如何正确编码吗?

提前致谢。

4

5 回答 5

3

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

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

void settings(void);

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

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

void settings();

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

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

于 2013-03-04T17:00:48.597 回答
1

快速解决方法是为settings()before添加一个前向声明,controls()如下所示:

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++ - 前向声明

于 2013-03-04T17:03:23.360 回答
0

问题是 settings() 是在 controls() 之后声明的,并且控件试图调用 settings()。但是,由于 settings() 尚不存在,因此无法这样做。

您可以将 settings() 的定义移到 controls() 之前,也可以在 controls() 之前执行 settings() 的前向声明。

void settings(); //forward declaration
void controls() { 
  .....
}
void settings() {
  .... 
}
于 2013-03-04T17:03:28.397 回答
0

您是否首先在头文件中声明了 settings() ?此外,如果这些方法在头文件中声明,我看不到您将任何方法的范围限定为类名或命名空间。

如果您不需要头文件,无论出于何种原因,请更改您编写的顺序。在使用之前定义 settings() 。

于 2013-03-04T17:03:29.410 回答
0

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

于 2013-03-04T17:02:39.523 回答