基本概念
一般使用继承或组合(聚集)
继承一般是新旧关系;组合一般是包含关系
成员对象的构造过程和析构过程
示例代码
#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;
}