gpt4 book ai didi

c++ - 动态转换 C++ 的奇怪问题

转载 作者:太空狗 更新时间:2023-10-29 23:22:55 25 4
gpt4 key购买 nike

<分区>

我刚接触 C++,正在做一个实现某些继承的小项目。基本上可以总结如下:

//.h file
class Food{
public:
Food();
virtual ~Food();
};

class Animal{
public:
Animal();
virtual ~Animal();
virtual void eat( Food f);
};

class Meat : public Food{
public:
Meat();
~Meat();
};

class Vegetable : public Food{
public:
Vegetable();
~Vegetable();
};

class Carnivore : public Animal{
public:
Carnivore();
~Carnivore();
void eat(Food f);
};

//.cpp file

Food::Food()
{
do something;
}

Food:~Food()
{
do something;
}

Animal::Animal()
{
do something;
}

Animal::~Animal()
{
do something;
}

Meat::Meat()
{
do something;
}

Meat::~Meat()
{
do something;
}

Vegetable::Vegetable()
{
do something;
}

Vegetable::~Vegetable()
{
do something;
}

Carnivore::Carnivore()
{
do something;
}

Carnivore::~Carnivore()
{
do something;
}

void Carnivore::eat(Food f)
{
Meat* m = dynamic_cast<Meat*>(&f);
if(m != 0) cout << "can eat\n";
else cout << "can not eat\n";
}

//main.cpp

int main()
{
Animal* a;
Food* f;

Meat m;
Vegetable v;
Carnivore c;

a = &c;
f = &v;
a->eat(*f);
f = &m;
a->eat(*f);


return 1;
}

输出:

can not eat
can not eat

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