由于看了《Inside C++对象模型》这本书,顺手把学到的东西记下来,这样跟深刻一些。
我们来看看default constructor这节,在课本上,我们都学到了,如果在一个class 中没有defaulst constructor,在class object 中compiler将会给我们自动生成一个defalut constructor。这个说法不太严谨。是不是当我们需要时,compiler就会给我们合成呢。答案是否定的。能否合成一个default constructor,要看是谁需要这个default constructor,compiler or us?
For example:
class people
{
public:
int age;
.......
}
void Fun ()
{
people it;
if(it.age>...)
{
...
}
...
}
看看这个例子,当我们需要这个age member时,compiler是否会给我们初始化这个值呢?No,this is just what we need.
compiler会视而不见,不会管我们的闲事,因此也就不会为我们合成default constructor。
下面我们就看看一看,什么时候compiler会给我们合成default constructor.
1.带有class members 中有 带有default constructor的member object。
但是这个default constructor 只会在constuctor被调用的的时候合成,而且合成的default constructor只满足compiler需要。
我们再看个例子
class people
{
public:
people();
public:
int age;
.......
}
class company
{
public:
String name;
people employer;
...
}
void fun()
{
company cp; //这个时候才合成default constructor
if(cp.name.....)
. ..
...
}
此时compiler是不会给我们初始化这个值的,compiler所执行的代码可参考为:
inline company:: company()
{
employer.people::people();
}
因此我们需要一个explicit default constructor,但是这样,compiler就不会合成一个default constructor,但是它将上面的代码insert into your default constructor.
寝室快停电了,还有点事,先保存再说,下面还有3点没说,待下篇吧。