文章标题

#include <iostream>
#include <string>
using namespace std;

class Base
{
public:
    Base()
    {
        cout << "Base::基类" << endl;
    }
    ~Base()
    {
        cout << "调用基类的析构函数" << endl;
    };
    // 成员初始化列表语法
    Base(string x,string y):x(x),y(y)
    {
        cout << "Base::传递参数的基类构造函数" << endl;
    };

private:
    string x;
    string y;


};
class Derive:public Base    // 派生   公有派生
// 使用公有派生,基类的公有成员将成为派生类的公有成员。
// 基类的私有部分也将成为派生类的一部分,但只能通过基类的公有和保护方法访问。
// 派生类不能直接访问基类的私有成员,而必须通过基类方法进行访问。
{
public:
    Derive()
    {
        cout << "Derive::派生" << endl;
    }
    ~Derive()
    {
        cout << "调用派生类的析构函数" << endl;
    };
    // 成员初始化列表语法
    Derive(string z,string str2,string str3):Base(str2,str3),z(z)
    {
        //this.z = z;

        cout << "Derive::传递参数的派生类的构造函数" << endl;
    }
    Derive(string z,const Base & base):Base(base),z(z)
    {

        cout << "Derive::传递参数的派生类的构造函数" << endl;
    }
private:
    string z;
};


int main()
{
    // 基类对象应该在程序进入派生类构造函数之前被创建。
    Derive *derive;
    derive = new Derive("10","10","10");
    delete derive;
    cout << endl;
    cout << "********************" << endl;

    Base *base = new Base("20","20");
    derive = new Derive("BG_80",*base);
    //delete base;
    // 派生类过期时,程序首先调用派生类的析构函数,然后调用基类的析构函数。
    delete derive;              // 这里要不要delete base? 应该不要

    system("pause");
    return 0;
}

如果子类中没有默认无参构造函数,那么像下面这样调用会报错

#include <iostream>
using namespace std;
class A
{
public:
    int a;
    int b;
// A()
// {
//  cout<<"A Constructed 1\n";
// }
A(int a,int b)
{
    this->a=a;
    this->b=b;
    cout<<"A Constructed 2\n";
}
};
class B:public A
{
public:
    int c;
    int d;
B()
{
    cout<<"B Constructed 1\n";
}
B(int c,int d):A(100,200)
{
    this->c=c;
    this->d=d;
    cout<<"B Constructed 2\n";
}
};
int main()
{
    // B b(1,1);
    // cout << "b.a = " << b.A::a <<" " << "b.b = " << b.A::b << endl;
    // cout << "b.a = " << b.a <<" " << "b.b = " << b.b << endl;
    // cout << "b.c = " << b.c <<" " << "b.d = " << b.d << endl;
    B b;

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值