我正在浏览Cprogramming.com上的随机页面,注意到构造函数和析构函数教程/示例页面。他们使用了以下定义构造函数的方法:
class String
{
private:
char *str;
int size;
public:
String() : str(NULL), size(0) { } // <- This statement
String(int size) : str(NULL), size(size) { // <- And this one
str = new char[size];
}
}
我一直在使用传统的构造函数定义方式和神奇的this
指针:
String() {
this->str = NULL;
this->size = 0;
}
String(int size) {
this->size = size;
this->str = new char[size];
}
除了明显的代码更小(行数更少)之外,第一次声明是否有任何额外的好处?
PS:我已经好几年没有写过C++了。