2010-09-26 65 views
0

我很新編程&遇到了我正在閱讀的書中的一個程序。我得到一個編譯錯誤。需要一些幫助,初始化指向成員函數的指針數組

錯誤說「可變大小的物體‘ptrFunc’可能不被初始化。」(它指向數組的結尾)

請指教,什麼是錯的it.Thanks提前。

#include<iostream> 

using namespace std; 

class cDog 
{ 
    public: 
      void speak() const 
      { 
       cout<<"\nWoof Woof!!"; 
      } 
      void move() const 
      { 
       cout<<"\nWalking to heel..."; 
      } 
      void eat() const 
      { 
       cout<<"\nGobbling food..."; 
      } 
      void growl() const 
      { 
       cout<<"\nGrrrgh..."; 
      } 
      void whimper() const 
      { 
       cout<<"\nWhinig noises..."; 
      } 
      void rollOver() const 
      { 
       cout<<"\nRolling over..."; 
      } 
      void playDead() const 
      { 
       cout<<"\nIs this the end of little Ceaser?"; 
      } 
}; 

int printMenu(); 

int main() 
{ 
    int selection = 0; 
    bool quit = 0; 
    int noOfFunc = 7; 
    void (cDog::*ptrFunc[noOfFunc])() const = { 

    &cDog::eat, 
    &cDog::growl, 
    &cDog::move, 
    &cDog::playDead, 
    &cDog::rollOver, 
    &cDog::speak, 
    &cDog::whimper 
    }; 

    while(!quit) 
    { 
     selection = printMenu(); 

     if(selection == 8) 
     { 
      cout<<"\nExiting program."; 
      break; 
     } 
     else 
     { 
      cDog *ptrDog = new cDog; 
      (ptrDog->*ptrFunc[selection-1])(); 
      delete ptrDog; 
     } 
    } 
    cout<<endl; 

    return 0; 
} 

int printMenu() 
{ 
    int sel = 0; 

    cout<<"\n\t\tMenu"; 
    cout<<"\n\n1. Eat"; 
    cout<<"\n2. Growl"; 
    cout<<"\n3. Move"; 
    cout<<"\n4. Play dead"; 
    cout<<"\n5. Roll over"; 
    cout<<"\n6. Speak"; 
    cout<<"\n7. Whimper"; 
    cout<<"\n8. Quit"; 
    cout<<"\n\n\tEnter your selection : "; 
    cin>>sel; 

    return sel; 
} 

回答

2
void (cDog::*ptrFunc[noOfFunc])() const = { 

noOfFunc不是常量限定;您需要將其聲明爲const int以將其用作數組大小(在編譯時必須知道數組的大小)。

但是,當您像在這裏一樣聲明一個初始化程序時,您可以省略大小;編譯器會根據初始化程序中元素的數量來確定它。你可以簡單地說:

void (cDog::*ptrFunc[])() const = { 
+0

嘿thanks.Ok我想我再得到it.Thanks。 – Ramila 2010-09-26 02:19:01

0

`更改它作爲

void (cDog::*ptrFunc[7])() const = 

void (cDog::*ptrFunc[])() const = 
+0

嘿謝謝,我想我現在明白了。再次感謝。 – Ramila 2010-09-26 02:28:56