类之间是否存在直接的关联关系?
//43-1.cpp #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; }
组合关系特点:
面向对象中的继承指类之间的父子关系
c++中通过下面的方式描述继承关系
class Parent { int mv; public: void method(); }; class child : public Parent { };
//43-2.cpp #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." << endl; } }; int main() { Child c; c.hello(); c.method(); return 0; }
重要规则:
继承是C++中代码复用的重要手段。通过继承,可以获得父类的所有功能,并且可以在子类中重写已有功能,或者添加新功能。
//43-3.cpp #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; } }; class HPBook : public Computer { string mOS; public: HPBook() { mOS = "windows 8"; } void install(string os) { mOS = os; } void OS() { cout << mOS << endl; } }; class MacBook : public Computer { public: void OS() { cout << "Mac OS" << endl; } }; int main() { HPBook hp; hp.power(); hp.install("Ubuntu 16.04 LTS"); hp.OS(); cout << endl; MacBook mac; mac.OS(); return 0; }