两种类型的构造函数/哪一种更好
Two types of constructors / which one is better?
假设同一个类有两个版本:
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
或引用,那么除了将其放入初始化列表之外别无选择。
我更喜欢将函数体保持为单独的行,以防我需要在其中一个上设置断点。
相关文章:
- 寻找一种更好的方法来表示无符号字符数组
- 使用移位的无符号数字作为数组的索引号是一种很好的做法
- C++|以一种很好的方式将树(不一定是二进制的)打印到stdout
- 静态常量与常量局部变量,哪一个性能更好
- 接口在C++中是一种很好的做法吗?
- 为许多类可能需要的所有常量变量制作独立的头文件是否是一种很好的做法?
- 需要帮助从12个字节生成新的24字节RGB查找阵列,或者是一种更好的编码方法
- 有没有一种更快的方法,从特定的数字池中获取随机数
- 有没有一种很好的方法来实现具有默认失败情况的条件类型?
- 需要一种更好的方法来编写电源函数
- C 向量异常处理:哪一种是抛出out_of_range()的更好方法以及原因
- 两种数字比较方法中哪一种更有效
- (无符号字符)str 与 str + 0xff 或(无符号整数)值与值 + 0xffff 中的哪一种更快和首选
- ADL与范围分辨率——更喜欢哪一种
- 在正则语法和上下文无关语法中,哪一种更强大.也请告诉我原因
- 哪一种方法是更快的向量(插入后排序)或集合
- 一种更好的数组移位算法
- c++ OOP哪一种方式给构造函数赋值更好
- 找出后缀数组的两种算法中哪一种更快,为什么?
- 两种类型的构造函数/哪一种更好