c++基础三

1.继承

继承表示,子类可以获取父类的属性和方法,然后可以写子类独有的属性和方法,或者修改父类的方法。类可以继承父类的公共成员(public),但不能继承私有成员(private),私有成员只能在父类内部访问。

1.1 案例一单继承

#include <iostream>

using namespace std;
class friut
{
   
public:
    friut()
    {
   
        cout << "fruit constructor" << endl;
    }

    ~friut()
    {
   
        cout << "fruit destructor" << endl;
    }

    void show()
    {
   
        cout << "fruit show" << endl;
    }

};

class Apple: public friut
{
   
public:
    Apple()
    {
   
        cout << "Apple constructor" << endl;
    }
    ~Apple()
    {
   
        cout << "Apple destructor" << endl;
    }
};

int main()
{
   
    Apple apple;
    apple.show();
    return 0;
}
//fruit constructor
//Apple constructor
//fruit show
//Apple destructor
//fruit destructor

通过上面的代码可以知道,子类apple继承了父类fruit公共属性,子类可以调用show方法。

1.2.1案例二多继承,各个父类成员变量不重名

#include <iostream>
using namespace std;

class base1
{
   
public:
    int a;
    base1(int x)
    {
   
        a = x;
        cout << "base1 constructor" << endl;
    }
};

class base2
{
   
public:
    int b;
    base2(int y)
    {
   
        b = y;
        cout << "base2 constructor" << endl;
    }
};

class test:public base1, public base2
{
   
public:
    int c;
    test(int x, int y, int z):base1(x), base2(y)
    {
   
        c = z;
        cout << "test constructor" << endl;
    }

    void show()
    {
   
        cout << "a: " << a << ", b: " << b << ", c: " << c << endl;
    }

};


int main()
{
   
    test t(1, 2, 3);
    t.show();
    return 0;
}
//base1 constructor
//base2 constructor
//test constructor
//a: 1, b: 2, c: 3

通过案例可以知道,test继承了base1, base2两个父类,并且拥有了两个父类的属性,这就是多继承。

1.2.3案例三多继承,各个父类成员变量重名

#include <iostream>
using namespace std;

class base1
{
   
public:
    int a;
    base1(int x)
    {
   
        a = x;
        cout << "base1 constructor" << endl;
    }
};

class base2
{
   
public:
    int a;
    base2(int y)
    {
   
        a &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值