1

我见过 c++ 类构造函数以两种不同的方式初始化成员,但效果相同。假设我们有一个简单的类:

class myClass
{
public:
    myclass();//default constructor

private:
    int a;
    int b;
    bool c;
};

情况1:

myClass::myClass()
/* Default constructor */
{
    a=5;
    b=10;
    c=true;

    //do more here
}

案例二:

myClass::myClass()
/* Default constructor */

    :a(5),
    b(10),
    c(true)
{
    //do more in here
}

编译后两者有什么区别?即使没有区别,有没有“首选”的方式呢?

4

1 回答 1

3

第一个构造函数调用a,b,cfirst 的默认构造函数(基本上将它们分配给随机值),然后将它们分配给提供的值。第二个构造函数直接调用适当的构造函数a,b,c

一般来说,第二个构造函数更有效,因为成员被初始化一次,如果你有没有默认构造函数的成员,你必须以这种方式或在 C++11 中使用非静态成员初始化器来初始化它们。

于 2013-10-03T02:21:53.947 回答