【发布时间】:2021-09-29 08:26:07
【问题描述】:
我需要一些帮助来理解这个问题中使用的语法,以便我不久前进行评估。
将缺少的代码添加到Chicken和Egg,这样就完成了以下操作:
- Chicken 实现了 Bird 类。
- 鸡下蛋后会孵化成新鸡。
- 其他类型鸟类的卵应该孵化成其父类型的新鸟类。
- 第二次孵化鸡蛋会引发 std::logic_error。
这是代码模板:
#include <stdexcept>
#include <functional>
class Egg;
class Bird
{
public:
virtual ~Bird(){};
virtual Egg *lay() = 0;
};
class Egg
{
public:
Egg(std::function<Bird *()> createBird)
{
throw std::logic_error("Waiting to be implemented");
}
Bird *hatch()
{
throw std::logic_error("Waiting to be implemented");
}
};
class Chicken : public Bird
{
public:
Chicken()
{
}
Egg *lay()
{
throw std::logic_error("Waiting to be implemented");
}
};
#ifndef RunTests
int main()
{
Bird *chicken = new Chicken();
Egg *egg1 = chicken->lay();
Bird *childChicken1 = egg1->hatch();
}
#endif
这是我尝试完成的一些任务。
#include <stdexcept>
#include <functional>
#include <iostream>
using namespace std;
class Egg;
class Bird
{
public:
virtual ~Bird(){};
virtual Egg *lay() = 0;
};
class Egg
{
int hatchCount = 0;
public:
Egg(std::function<Bird *()> createBird)
{
throw std::logic_error("Waiting to be implemented");
}
Bird *hatch()
{
if (hatchCount > 0)
{
throw std::logic_error("This egg already hatched!");
}
hatchCount++;
}
};
class Chicken : public Bird
{
public:
Chicken()
{
}
Egg *lay()
{
return Egg(Chicken());
}
};
#ifndef RunTests
int main()
{
Bird *chicken = new Chicken();
Egg *egg1 = chicken->lay();
Bird *childChicken1 = egg1->hatch();
}
#endif
显然不多。我确实从 Bird 类中理解了 Chicken 的类扩展。我迷失了一些使用的关键字/语法(虚拟?函数
为此:
Egg *egg1 = chicken->lay();
我们是否试图通过访问某个地方的变量来创建一个新的 egg 对象?
如果有人能阐明这个问题,我将不胜感激!
【问题讨论】: