C++中派生类隐式调用与显式调用基类的构造函数

通过派生类的构造函数调用基类的构造函数有两种方式,隐式和显式两种。
所谓隐式方式就是在派生类的构造函数中不指定对应的基类的构造函数,这个时候调用的是基类的默认构造函数(即含有默认参数值或不带参数的构造函数)。而所谓显式方式,就是在派生类的构造函数中指定要调用的基类的构造函数,并将派生类构造函数的部分参数值传递给基类构造函数。注:除非基类有默认的构造函数,否则必须采用显式调用方式
#include <iostream>
using namespace std;
class A
{
public:
    A(int x = 0,int y = 0)
    {
        a = x;
        b = y;
    }
private:
    int a;
    int b;
};
//基类A有默认的构造函数,可以隐式调用
class B:public A
{
public:
    B(int z = 0)
    {
        c = z;
    }
private:
    int c;
};
int main()
{
    B b1;
    return 0;
}
#include <iostream>
using namespace std;
class A
{
public:
    A(int x,int y)
    {
        a = x;
        b = y;
    }
private:
    int a;
    int b;
};
//基类A没有默认的构造函数,其现有的构造函数需要传递参数,通过
//派生类构造函数调用A构造函数时必须如下显式调用
class B:public A
{
public:
    B(int x,int y,int z):A(x,y)
    {
        c = z;
    }
private:
    int c;
};
int main()
{
    B b1(1,2,3);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_38314865/article/details/105946351