虚函数不允许多函数重载吗?

时间:2010-09-21 08:56:09

标签: c++

我的程序编译得很好,但在调用重载函数时会被转储。下面是该程序的输出:

FoodID supplied=1
FoodBase constructor called
In K constructor
In Omlette constructor
Omlette handler constructor called
In prepare() Omlette Handler
Mix called
K Prepare called
K Egg called
DonePreparing called
In egg() Omlette Handler
Segmentation fault (core dumped)

我正在尝试重载名为“egg”的纯虚函数。 egg函数需要有两种类型:一种不采用变量,另一种采用整数。占用整数崩溃的那个。帮助

#include<iostream>
#include<cstdlib>
using namespace std;

class K
{
    public:
    K() {cout<<"In K constructor"<<endl;}

    protected:
    void kPrepare() {cout<<"K Prepare called"<<endl;}
    void kEgg() {cout<<"K Egg called"<<endl;}
};

class Omlette : public K
{
    public:
    Omlette() {cout<<"In Omlette constructor"<<endl;}

    protected:
    void doPreparation()
    {
        mix();
        kPrepare();
        kEgg();
        donePreparing();
    }
    void mix() {cout<<"Mix called"<<endl;}
    void donePreparing() {cout<<"DonePreparing called"<<endl;}  
};

class FoodBase
{
    public:
    virtual void prepare()=0;
    virtual void egg()=0;
    virtual void egg(int)=0;

    FoodBase() {cout<<"FoodBase constructor called"<<endl;}

};

class OmletteHandler : public FoodBase, Omlette
{   
    public:
    OmletteHandler() {cout<<"Omlette handler constructor called"<<endl;}
    void prepare() 
    {
        cout<<"In prepare() Omlette Handler"<<endl;
        doPreparation();//from Omlette class
    }
    void egg() {cout<<"In egg() Omlette Handler"<<endl;}
    void egg(int i) {cout<<"In egg("<<i<<") Omlette Handler"<<endl;}
};

class Food
{
    public:
    FoodBase *base;

    Food(int foodID)//getting foodID from commandline just for testing purpose
    {
        OmletteHandler immediate;//changed from 'imm' to 'immediate'
        base=&immediate;
    }//Food

    void prepare() {base->prepare();}
    void egg() {base->egg();}
    void egg(int i) {base->egg(i);}
};

int main(int argc, char *argv[])
{
    int foodID=1;
    if (argc>1) {foodID = atoi(argv[1]);}

    cout<<"FoodID supplied="<<foodID<<endl; 

    Food f(foodID);
    f.prepare();
    f.egg();
    f.egg(10);

}//main

1 个答案:

答案 0 :(得分:7)

在Food构造函数中,您在堆栈上创建一个OmeletteHandler,一旦函数退出,它就会被销毁。

Food(int foodID)//getting foodID from commandline just for testing purpose 
{ 
    OmletteHandler imm; 
    base=&imm; 
}//

你可以改为base = new OmeletteHandler(),(别忘了稍后删除指针,否则你会有内存泄漏)。