两种类型的构造函数/哪一种更好

Two types of constructors / which one is better?

本文关键字:哪一种 更好 构造函数 类型 两种      更新时间:2023-10-16

假设同一个类有两个版本:

1。

#include <iostream>
using namespace std;
class Simple
{
public:
    Simple() { }
    Simple(int c)
    { 
        data = c;
        cout << data << endl; 
    }
private:
    int data;
};
int main()
{
    Simple obj(3);
    return 0;
}

2。

#include <iostream>
using namespace std;
class Simple
{
public:
    Simple() { }
    Simple(int c) : data(c) { cout << data << endl; }
private:
    int data;
};
int main()
{
    Simple obj(3);
    return 0;
}

编译、运行并给出相同的结果。应该使用哪一个,它们之间有什么内在的区别吗?谢谢。

最好使用初始化列表来初始化成员变量,这就是它的作用。在复杂对象的情况下,也可能有效率上的好处,因为您可以跳过默认初始化。如果成员没有默认构造函数,或者是const或引用,那么除了将其放入初始化列表之外别无选择。

我更喜欢将函数体保持为单独的行,以防我需要在其中一个上设置断点。