第一个使用所谓的初始化列表。
当你进入构造函数的主体时,所有的类成员都必须已经被构造(所以它们可以被使用)。所以如果你有这个:
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;
};