我剛剛在Cprogramming.com上看到隨機頁面,並注意到Constructors and Destructors教程/示例頁面。他們使用定義構造函數的方法如下:這個構造函數定義有什麼好處
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++中編寫了一些東西以來,已經有好幾年了。
http://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list –