我看到有人在初始化列表中的成员变量后面加上括号,不知道为什么会这样做?
例如,在头文件中有一个STL容器:
class A{
public:
A();
...
private:
vector<string> v;
}
并且在源文件中:
A::A() : v() {}
我的问题是什么是v(),为什么人们这样做,因为它看起来v没有初始化为一个值。
我看到有人在初始化列表中的成员变量后面加上括号,不知道为什么会这样做?
例如,在头文件中有一个STL容器:
class A{
public:
A();
...
private:
vector<string> v;
}
并且在源文件中:
A::A() : v() {}
这将运行成员的默认构造函数或初始值设定项(对于普通类型)。
在此情况下,它将默认构造向量。由于这是默认构造函数,所以在这里不是必要的。v
如果没有初始化程序,则会被默认构造。
class Example {
private:
int defaultInt;
vector<int> defaultVector;
int valuedInt;
vector<int> sizedVector;
public:
Example(int value = 0, size_t vectorLen = 10)
: defaultInt(), defaultVector(), valuedInt(value), sizedVector(vectorLen)
{
//defaultInt is now 0 (since integral types are default-initialized to 0)
//defaultVector is now a std::vector<int>() (a default constructed vector)
//valuedInt is now value since it was initialized to value
//sizedVector is now a vector of 'size' default-intialized ints (so 'size' 0's)
}
};
为了好玩和开心,你还可以执行thirdVector(vectorLen, value)
来获得一个具有vectorLen
个元素且值为value
的vector
。(因此,Example(5, 10)
将使thirdVector
成为一个由10
个值为5
的元素组成的向量。)
struct A
{
int t;
A() : { /* value of t undefined */ }
}
struct A
{
int t;
A() : t() { /* value of t is t's default value of 0 */ }
}
v()
。但是如果你想在列表中提及它,你必须加上括号。 - Andy Prowl