需要一些帮助来初始化成员函数的指针数组

时间:2010-09-26 02:08:35

标签: c++

我是编程和编程的新手。在我正在阅读的书中遇到了一个程序。我在其中遇到编译错误。

错误说“可变大小的对象'ptrFunc'可能无法初始化。”(它指向数组的末尾)

请告知,有什么问题。谢谢。

#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 个答案:

答案 0 :(得分:2)

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

noOfFunc不符合const标准;您需要将其声明为const int以将其用作数组大小(必须在编译时知道数组的大小)。

但是,当你像这里一样声明一个像初始化器一样的数组时,可以省略大小;编译器将根据初始化程序中的元素数来确定它。你可以简单地说:

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

答案 1 :(得分:0)

`将其更改为

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

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