简体   繁体   中英

Need some help with initializing an array of pointers to member functions

I'm very new to programming & came across a program in a book i'm reading.I get a compile error in it.

The error says "variable-sized object 'ptrFunc' may not be initialized".(it points to the end of the array)

Please advise,what is wrong in it.Thanks in advance.

#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;
}
void (cDog::*ptrFunc[noOfFunc])() const = {

noOfFunc is not const-qualified; you would need to declare it as a const int to use it as an array size (the size of an array has to be known at compile time).

However, when you declare an array like an initializer as you do here, you can omit the size; the compiler will determine it from the number of elements in the initializer. You can simply say:

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

`Change it as

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM