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

Confused by parameters example given in college lecture

本文关键字:参数 大学      更新时间:2023-10-16

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

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(这是使其工作的关键位(,因此允许编译器自己隐式创建临时BoundingBox - 它适当地这样做,然后创建Enemy对象。

添加explicit将导致编译失败;这样做并观察收到的错误消息将是建设性的。我怀疑这也可能是未来讲座的主题。

通常,建议将构造函数标记为可以将单个参数(考虑默认值(作为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
        {}
};