构造函数的一些需要注意的特性(一)

1.如果一个类,你没有定义构造函数,那么系统默认会有一个无参的构造函数但如果你定义了一个有参的构造函数,为了保证正确性,系统不会创建无参构造函数,这时候,如果你还想允许无参构造,就必须显式的声明一个。

#include"stdafx.h"
#include<iostream>
#include<stdlib.h>
using namespace std;

class B0
{
public:
   B0(int n)
{
   nV=n;
}
int nV;
};
class B1:public B0
{
public:
   B1(int a)//:B0(0) 如果这里没有初始化B0,那么就提示错误了,原因同上
{
   nV=a;
}
int nV1;
};

2.一个派生类只能初始化它的直接基类,而不能间接使用非虚拟基类

#include"stdafx.h"
#include<iostream>
#include<stdlib.h>
using namespace std;

class B0
{
public:
   B0(int n)
{
   nV=n;
}
int nV;
};
class B1:public B0
{
public:
   B1(int a):B0(0)//必须初始化B0,因为已不提供默认的构造函数了
{
   nV=a;
}
int nV1;
};

class B2:public B0
{
public:
   B2(int a):B0(0) //必须初始化B0,因为已不提供默认的构造函数了
{
   nV=a;
}
int nV2;
};

class D:public B1,public B2
{
public:
    D(int a):B1(0),B2(0),B0(0) //此处就是错误了,B0不是直接的基类是不能初始化,除非虚基类
    {

    }
int nVd;
}

猜你喜欢

转载自blog.csdn.net/l93919861/article/details/84347838