对大学讲座中给出的参数示例感到困惑
Confused by parameters example given in college lecture
很抱歉发布这样一个具体的问题,但我对大学里给出的一个示例问题感到困惑。问题是:
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
{}
};
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 对大学讲座中给出的参数示例感到困惑