HoK*_*y22 3 c++ initialization member-variables
我看到人们在初始化列表中的成员变量后放置一个括号.我想知道为什么人们这样做?
例如,我在头文件中有一个STL容器:
class A{
public:
A();
...
private:
vector<string> v;
}
Run Code Online (Sandbox Code Playgroud)
在源文件中:
A::A() : v() {}
Run Code Online (Sandbox Code Playgroud)
我的问题是什么是v()以及为什么人们这样做,因为看起来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)
}
};
Run Code Online (Sandbox Code Playgroud)
对于踢腿和傻笑,你也可以做thirdVector(vectorLen, value)一个vector带有vectorLen值的元素value.(因此Example(5, 10)会使元素thirdVector向量10值得5.)