第一種使用所謂的一個initialization list。
當你輸入構造函數的主體時,所有的類成員都必須被構造(所以它們可以被使用)。所以,如果你有這樣的:
class Foo
{
public:
Foo()
: str() // this is implicit
{
str = "String.";
}
private:
std::string str;
};
所以,str
被構建,然後分配。最好是:
class Foo
{
public:
Foo()
: str("String.")
{
}
private:
std::string str;
};
因此str
得到直接構建。這對你的情況並沒有什麼不同,因爲指針沒有構造函數。
在構造函數中使用初始化列表而不是運行代碼通常被認爲是很好的做法。 初始化列表應該用於初始化,構造函數應該用於運行代碼。
另外,爲什麼要使用指向字符串的指針?如果你想要一個字符串,使用一個字符串;不是指向字符串的指針。機會是,你實際上想要一個字符串。
更多關於初始化列表:
初始化列表有更多的用途比類的初始化剛剛成員。它們可以被用來傳遞參數爲基礎的構造函數:
class Foo
{
public:
Foo(int i) { /* ... */ }
}
class Bar
: public Foo
{
public:
Bar()
: Foo(2) // pass 2 into Foo's constructor.
// There is no other way of doing this.
{
/* ... */
}
};
或常量成員:
class Foo
{
public:
Foo()
: pi(3.1415f)
{
pi = 3.1415f; // will not work, pi is const.
}
private:
const float pi;
};
或參考:
class Foo
{
public:
Foo(int& i)
: intRef(i) // intRef refers to the i passed into this constructor
{
intRef = i; // does *not* set intRef to refer to i!
// rather, it sets i as the value of
// the int intRef refers to.
}
private:
int &intRef;
};
這不完全相同,因爲如果你做後者,你不能創建一個常量圖像。在這種情況下可能不是你想要做的事情,但對於更輕量級的類型可能有意思。 – 2009-08-06 07:29:22
如果你有一個const圖像,你可能也需要一個const m_sFileName,所以我沒有看到問題。 – MSalters 2009-08-06 07:53:24