9
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 ),
            child( 0 ),
            g( 0.0f ),
            h( 0.0f ),
            f( 0.0f )
    {
    }

代替

    Node()
    {
        parent = null;
        child = null;
        g = 0.0f;
        h = 0.0f;
        f = 0.0f;
    }

谢谢 :)

4

5 回答 5

14

对于普通旧数据 (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 指出引用的问题。

于 2011-04-19T10:22:01.023 回答
6

由于在某些情况下您确实需要或出于性能原因应该使用初始化列表来初始化成员,因此您应该保持一致并始终使用它。

需要使用初始化列表的示例是当聚合没有默认构造函数或当您有 const 成员时(是的,不常见,但允许)。

当你应该(但不是被迫)使用初始化列表的一个例子是当你有一个聚合对象并且以下几点是有效的:

  • 聚合有一个默认构造函数。
  • 您需要使用非默认值设置对象。
  • 聚合有一个构造函数,允许您设置所需的非默认值。

那么 - 为什么你不应该使用它呢?

于 2011-04-19T10:49:06.110 回答
3

首选初始化列表

于 2011-04-19T10:33:45.533 回答
2

主要是因为性能问题。

在这里讨论。

于 2011-04-19T10:23:53.600 回答
1

主要原因是对象有效性和类不变量。另一个原因是易用性。

如果你把所有东西都放在构造函数中,那么当构造函数完成时,你就可以保证一个有效的节点。如果您必须单独设置所有实例变量,则可能会因为程序员忘记或其中一个分配引发异常而使某些变量未初始化的节点。后者不会发生在您的情况下,但通常会发生。如果节点未完全初始化,则无法保证其行为与您预期的一样。

于 2011-04-19T10:26:18.973 回答