有四种情况下应该使用初始化表达式来初始化成员:
1:初始化const成员
常量必须在构造函数的初始化列表中初始,或将其设为static
Wrong:
Class A{
const int size =0; }
Right:
class A{A(){
const int size =9;
}};
OR
class A {
static const int size = 9;
}
2:初始化引用成员
3:当调用基类的构造函数,而它拥有一组参数时
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#include <vector>
#include <iostream>
using
namespace
std;
class
iStack
{
public
:
iStack(
int
capacity ) : _stack( capacity ), _top( 0 ) {}
//冒号后面的内容全然不懂什么意思,烦请讲解
bool
pop(
int
&value );
bool
push(
int
value );
bool
full();
bool
empty();
void
display();
int
size();
private
:
int
_top;
vector<
int
> _stack;
};
|
1
2
3
4
5
6
7
8
9
|
iStack(
int
capacity ) : _stack( capacity ), _top( 0 ) {}
//冒号后面的内容全然不懂什么意思,烦请讲解
//冒号后面的内容是初始化类的数据成员 _top;_stack;
也可以这样写
iStack(
int
capacity )
{
_stack( capacity );
_top( 0 );
}
|
4:当调用成员类的构造函数,而它拥有一组参数时