gpt4 book ai didi

c++ - 在初始化指向成员函数的指针数组方面需要一些帮助

转载 作者:行者123 更新时间:2023-11-28 03:55:30 25 4
gpt4 key购买 nike

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

错误说“可变大小的对象‘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 = {

关于c++ - 在初始化指向成员函数的指针数组方面需要一些帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3796323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com