繁体   English   中英

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

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

我对编程很陌生,在我正在读的书中碰到一个程序,但遇到编译错误。

错误显示“可变大小的对象'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;
}
void (cDog::*ptrFunc[noOfFunc])() const = {

noOfFunc不是const限定的; 您可能需要将其声明为const int才能将其用作数组大小(在编译时必须知道数组的大小)。

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

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

`将其更改为

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

要么

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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