我有一个名为Enemy的类,它有三个构造函数。它有一个默认值,一个带有统计数据和一个项目,另一个带有统计数据。我想要完成的是制作一个可以检测敌人是否有物品的功能。我想我可以轻松地创建另一个参数,其中包含他们拥有的项目数的整数值,但我真的希望能够只检查item参数,这样我就不需要创建另一个构造函数参数
或者,我想我也可以在我的item类中放入一个参数,该参数是1或0,并且允许检查以确定项是否存在。
我希望能够检测到某个项目的原因是,如果敌人确实有一个项目,则会在它告诉您该项目时发生一个序列,然后让您选择是否接受该项目。
答案 0 :(得分:0)
只要您始终可以省略使用默认值指定参数(例如Nothing),任务可能并不复杂。我们可以省略的参数应该是最后一个或前一个要省略的参数。所以,你所描述的相对容易适合:
class Stats
{
public:
// some stat methods and data
};
enum Item
{
Nothing,
Something1,
Something2,
Something3
};
class A
{
explicit A(Item item = Nothing);
A(const Stats& stats, Item item = Nothing);
};
A::A(Item item)
{
// in both constructors just recognize if the item is Nothing
if (item == Nothing)
{
// default, no item
}
else
{
// deal with an item
}
}
因此,您的客户端代码将能够:
// we imply item != Nothing here
A one; // default
A two(item); // with an item
A three(stats); // with stats
A four(stats, item); // with stats and an item
当然你应该以某种方式指定一个项目和统计数据。