2013-03-04 82 views
2

首先,這是我第一次編寫代碼,所以我是一個新手。錯誤'設置'沒有在此範圍內聲明

我正在爲使用devkit pro的nd編寫代碼,所以它全部用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()將得到激活。那麼是否有人知道如何正確編碼?

在此先感謝。

回答

2

在函數調用的那一刻,你的編譯器不知道這個函數的任何內容。有兩種方法可以使編譯知道您的功能:聲明定義

要聲明函數,必須將函數摘要(函數參數和返回值)放在編譯模塊的頂部,就像這樣。

void settings(void); 

要解決你的問題,你應該有它的第一個調用之前宣佈settings()功能。

在你的情況下,你應該聲明函數在文件的頂部。通過這種方式,編譯器將知道應該傳入的函數和參數。

void settings(); 

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

好文章,從開始,並獲得一些額外的細節:Declaration and definition at msdn

+0

感謝您的快速響應;有用! :-) – 2013-03-04 17:21:04

+0

我試圖解釋這個Mikhahail,但更好的解釋,從你:) – OriginalCliche 2013-03-04 21:27:36

0

settings()是局部功能。其定義後只能調用。移動上面的定義controls()或通過頭文件使其可用。

0

速戰速決將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++ - Forward declaration

+0

感謝您的反應快,太:-) – 2013-03-04 17:21:28

0

問題是設置()在controls()和控件試圖調用settings()後聲明的。但是,由於settings()尚不存在,因此無法這樣做。

您既可以在controls()之前移動settings()的定義,也可以在controls()之前執行settings()的前向聲明。

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

您是否首先在頭文件中聲明瞭設置()?另外,我沒有看到您將任何方法作爲您的類名稱或命名空間的範圍,因爲如果這些方法是在頭文件中聲明的,您可能會這樣做。

如果你不需要頭文件,無論出於何種原因,然後改變你寫的順序。在使用它之前定義設置()。

相關問題