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

1. 基类构造函数和派生类构造函数顺序    

      当创建一个派生类的对象时,系统首先自动创建一个基类对象,也就是说,在调用派生类构造函数创建派生类对象之前,系统首先调用基类的构造函数创建基类对象。当派生类对象生命期结束时,首先调用派生类的析构函数,然后调用基类的析构函数。简而言之,就是说,构造函数:基类->派生类。析构函数:派生类->基类

#include <iostream>
using namespace std;

int init(const std::string & info)
{
    std::cout << info << std::endl;
    return 0;
}

class A
{
    int m_x;
public:
    A():m_x(init("Init A::m_x"))
    {
        init("Call A::A()");
    }
};
class A1:public A
{
    int m_x;
    int m_y;
public:
    A1(): m_y(init("Init A1::m_y")), m_x(init("Init A1::m_x"))
  { 
    init("Call A1::A1()"); 
  } 
};

打印出来的结果为:

Init A::m_x
Call A::A()  ==>是因为隐式调用了父类的构造函数
Init A1::m_x ==>按照成员变量的声明顺序“而非”初始化列表指定的顺序来进行构造
Init A1::m_y
Call A1::A1()

2,通过派生类的构造函数调用基类的构造函数有两种方式,隐式和显式两种。
所谓隐式方式就是在派生类的构造函数中不指定对应的基类的构造函数,这个时候调用的是基类的默认构造函数(即含有默认参数值或不带参数的构造函数)而所谓显式方式,就是在派生类的构造函数中指定要调用的基类的构造函数,并将派生类构造函数的部分参数值传递给基类构造函数注:除非基类有默认的构造函数,否则必须采用显式调用方式
#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;
}

参考:https://blog.csdn.net/sinat_33718563/article/details/74002050

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,C++派生类的成员函数可以调用基类的成员函数。派生类可以继承基类的公有成员函数和公有成员变量。当派生类的成员函数需要调用基类的成员函数时,可以使用作用域解析运算符 `::` 来调用基类的成员函数。 例如,假设有一个基类 `BaseClass` 和一个派生类 `DerivedClass`,其 `BaseClass` 有一个公有成员函数 `baseFunc()`: ```cpp class BaseClass { public: void baseFunc() { std::cout << "This is a function in the base class." << std::endl; } }; class DerivedClass : public BaseClass { public: void derivedFunc() { std::cout << "This is a function in the derived class." << std::endl; baseFunc(); // 调用基类的成员函数 } }; ``` 在派生类的成员函数 `derivedFunc()` ,可以直接调用基类的成员函数 `baseFunc()`。如果基类的成员函数和派生类的成员函数同名,可以使用作用域解析运算符 `::` 来显式地指定调用基类的成员函数,例如: ```cpp class BaseClass { public: void baseFunc() { std::cout << "This is a function in the base class." << std::endl; } }; class DerivedClass : public BaseClass { public: void baseFunc() { std::cout << "This is a function in the derived class." << std::endl; BaseClass::baseFunc(); // 显式调用基类的成员函数 } }; ``` 在派生类的成员函数 `baseFunc()` ,可以使用 `BaseClass::baseFunc()` 显式调用基类的成员函数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值