35成员对象

35成员对象

基本概念

一般使用继承或组合(聚集)

继承一般是新旧关系;组合一般是包含关系

成员对象的构造过程和析构过程

示例代码

#include <iostream>

using namespace std;

class Engine
{
    //假设有大量代码
};

class NewEngine : public Engine    //继承
{

};

class Wheel
{
    //假设有大量代码
};

class Car
{
public:
    void Speed();
private:
    Engine a;       //成员对象,使用组合(聚集)
    Wheel b[4];
    int c;
};

class Disk
{
public:
    Disk()
    {
        this->volume = 0;
        cout << "缺省构造函数被调用!" << endl;
    }

    Disk(int volume)
    {
        this->volume = volume;
        cout << "构造函数被调用!" << this->volume << endl;
    }

    ~Disk()
    {
        cout << "硬盘的析构器被调用!" << endl;
    }
public:
    int volume;     //单位:TB,1TB=1000GB
};

class Computer      //使用组合,而不是继承,继承一般是新旧关系
{
public:
    Computer()
    {
        cout << "电脑的缺省构造器被调用!" << endl;
    }
    Computer(int DiskVolume): c1(DiskVolume),c2(DiskVolume)
    {
        cout << "电脑的构造器被调用!" << endl;
    }                      //必须对成员对象进行初始化

    void Print()
    {
        cout << "这台电脑的硬盘容量是:" << this->c1.volume << endl;
    }

    ~Computer()
    {
        cout << "电脑的析构器被调用!" << endl;
    }

private:
    Disk c1, c2;
};

int main()
{
    Computer e1, e2(8);         //建立对象之初便会调用构造器进行初始化
    e2.Print();

    cout << "成功!" << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值