1.组合关系
组合关系的特点
a.将其它类的对象作为当前类的成员使用
b.当前类的对象与成员对象的生命周期相同
c.成员对象在用法上与普通对象完全一致
eg:
#include <iostream>
#include <string>
using namespace std;
class Memory
{
public:
Memory()
{
cout << "Memory()" << endl;
}
~Memory()
{
cout << "~Memory()" << endl;
}
};
class Disk
{
public:
Disk()
{
cout << "Disk()" << endl;
}
~Disk()
{
cout << "~Disk()" << endl;
}
};
class CPU
{
public:
CPU()
{
cout << "CPU()" << endl;
}
~CPU()
{
cout << "~CPU()" << endl;
}
};
class MainBoard
{
public:
MainBoard()
{
cout << "MainBoard()" << endl;
}
~MainBoard()
{
cout << "~MainBoard()" << endl;
}
};
class Computer
{
Memory mMem;
Disk mDisk;
CPU mCPU;
MainBoard mMainBoard;
public:
Computer()
{
cout << "Computer()" << endl;
}
void power()
{
cout << "power()" << endl;
}
void reset()
{
cout << "reset()" << endl;
}
~Computer()
{
cout << "~Computer()" << endl;
}
};
int main()
{
Computer c;
return 0;
}
2.继承关系
面向对象中的继承关系指类之间的父子关系
a.子类拥有父类的所有属性和行为
b.子类是一种特殊的父类
c.子类对象可以当做父类对象使用
d.子类中可以添加父类没有的方法和属性
语法:
class Parent
{
int mv;
public:
void method ()
{
}
}
class Child : public Parent //描述继承关系
{
};
eg:
#include <iostream>
#include <string>
using namespace std;
class Parent
{
int mv;
public:
Parent ()
{
cout << "Parent()" << endl;
mv = 100;
}
void method ()
{
cout << "mv = " << mv << endl;
}
};
class Child : public Parent
{
public:
void hello()
{
cout << "I'm Child class" << endl;
}
};
int main()
{
Child c;
c.hello();
c.method();
return 0;
}
重要规则
a.子类就是一个特殊的父类
b.子类对象可以直接初始化父类对象
c.子类对象可以直接赋值给父类
eg: 上诉例子中的类
Child c;
Parent p1 = c;
Parent p2;
p2 = c;