第一个使用所谓的初始化列表 http://www.parashift.com/c++-faq-lite/ctors.html.
当您进入构造函数的主体时,必须已构造所有类成员(以便可以使用它们)。所以如果你有这个:
class Foo
{
public:
Foo()
: str() // this is implicit
{
str = "String.";
}
private:
std::string str;
};
So, str
被构造,然后分配。更好的是:
class Foo
{
public:
Foo()
: str("String.")
{
}
private:
std::string str;
};
So that 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;
};