2010-09-26 161 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