[英]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.