gpt4 book ai didi

c++ - 虚函数不允许多函数重载吗?

转载 作者:行者123 更新时间:2023-11-30 00:41:23 24 4
gpt4 key购买 nike

我的程序编译正常,但在调用重载函数时会发生核心转储。下面是程序的输出:

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

最佳答案

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

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

您可以改为执行 base = new OmeletteHandler(),(不要忘记稍后删除指针,否则会发生内存泄漏)。

关于c++ - 虚函数不允许多函数重载吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3758698/

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