我应该使用初始化程序列表还是在C构造函数中执行赋值?

前端之家收集整理的这篇文章主要介绍了我应该使用初始化程序列表还是在C构造函数中执行赋值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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指出引用的问题.

猜你在找的C&C++相关文章