gpt4 book ai didi

c++ - 对大学讲座中给出的参数示例感到困惑

转载 作者:行者123 更新时间:2023-11-30 02:33:30 28 4
gpt4 key购买 nike

很抱歉提出这样一个具体的问题,但我对大学里给出的示例问题感到困惑。问题是:

class BoundingBox {
private:
float m_width;
float m_height;
public:
BoundingBox(float width = 0, float height = 0) :
m_width(width), m_height(height) {}
};


class Enemy {
private:
EnemyType m_type;
BoundingBox m_box;

Enemy(BoundingBox const & box, EnemyType type = EnemyType::Boss) :
m_type(type);
m_box(box);
{}
};

问:Enemy 的以下构造是否合法?解释一下。

Enemy enemy1(10);

提供的答案说是,因为 10 作为 width 参数传入,height 使用默认值,同样使用默认值对于 EnemyType。但据我了解,该行:

BoundingBox const & box

期望将一个 box 对象传递给它,而不是它的构造函数的参数。

是我的讲师弄错了,还是我遗漏了什么?如果我误解了,你能给我提供一个链接来解释“幕后”发生的事情吗?我不知道这是构造对象的有效方法。我会问我的讲师,但他已经病了一个星期了,我在网上找不到任何关于基于参数的构造的信息。

最佳答案

是的,它很好并且可以编译(除了语法和对构造函数的访问)。

要创建类型Enemy,需要一个BoundingBox;特别是 Enemy 构造函数将参数作为 const& 接受,从而允许使用临时值。

要创建 BoundingBox,无需参数,可以使用一个 float 或两个 float。变化是因为在 BoundingBox 构造函数中提供了默认参数。构造函数未标记为 explicit(这是使其工作的关键位),因此允许编译器 implicitly create BoundingBox 本身是临时的 - 它会适本地执行此操作,然后创建 Enemy 对象。

添加explicit会导致编译失败;这样做对您很有建设性,并观察您收到的错误消息。我怀疑这也可能是 future 讲座的主题。

通常,建议将可以采用单个参数(考虑默认值)的构造函数标记为 explicit,从而防止未知(或看不见的)转换。如果需要隐式转换,则不要添加 explicit


已清除语法问题的代码;

class BoundingBox {
private:
float m_width;
float m_height;
public:
/*explicit*/ BoundingBox(float width = 0, float height = 0) :
// ^^^^^^^ experiment with and without this being present
m_width(width), m_height(height) {}
};

class Enemy {
private:
EnemyType m_type;
BoundingBox m_box;
public:
// ^^^ added to allow access to the constructor
Enemy(BoundingBox const & box, EnemyType type = EnemyType::Boss) :
m_type(type),
// ^ syntax here
m_box(box)
// ^ syntax here
{}
};

关于c++ - 对大学讲座中给出的参数示例感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35360845/

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