我应该使用初始化程序列表还是在C构造函数中执行赋值?
发布时间:2020-12-16 03:18:44 所属栏目:百科 来源:网络整理
导读:class Node{public: Node *parent; // used during the search to record the parent of successor nodes Node *child; // used after the search for the application to view the search in reverse float g; // cost of this node + it's predecessors fl
class Node { public: Node *parent; // used during the search to record the parent of successor nodes Node *child; // used after the search for the application to view the search in reverse float g; // cost of this node + it's predecessors float h; // heuristic estimate of distance to goal float f; // sum of cumulative cost of predecessors and self and heuristic Node() : parent( 0 ),child( 0 ),g( 0.0f ),h( 0.0f ),f( 0.0f ) { } UserState m_UserState; }; 为什么我们应该使用构造函数 Node() : parent( 0 ),f( 0.0f ) { } 代替 Node() { parent = null; child = null; g = 0.0f; h = 0.0f; f = 0.0f; } 谢谢 :) 解决方法
对于简单的旧数据(POD),这没有什么好处,但一旦开始使用引用或组合类,它会有所不同:
class Foo { Bar bar; public: // construct bar from x Foo(int x) : bar(x) { } }; 与 Foo::Foo(int x) { // bar is default-constructed; how do we "re-construct" it from x? bar = x; // requires operator=(int) on bar; even if that's available,// time is wasted default-constructing bar } 有时,一旦构造了对象,你甚至不会有一种“重新构建”对象的方式,因为类可能不支持setter或operator =. const成员肯定不能“重新构建”或重置: class FooWithConstBar { const Bar bar; public: Foo(int x) { // bar is cast in stone for the lifetime of this Foo object } }; 编辑:感谢@Vitus指出引用的问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |