常常在使用C++ Class,但是常常會忘記架構,以下使用個簡單的範例來展示class的基本結構。
- #include <iostream>
- #include <string>
- #include <cstdlib>
- using namespace std;
- ////////////////////////////////////////////////////
- class Base
- {
- public:
- //constructor
- Base(int num=0,string str=""):
- base_id(num), base_name(str){
- cout<<"Base construction\n";
- }
-
- //Destructor
- //若Base class的destructor沒有設定為virtual
- //則derived clss的destructor不會被呼叫,無法運作
- virtual ~Base(){
- cout<<"Base destroyed\n";
- }
-
- //overloading
- virtual void print(){
- cout<<"base id = "<<base_id
- <<" name = "<<base_name<<endl;
- }
-
- //abstract method, 必須是virtual,否則無法compile
- virtual void printall() = 0;
-
- protected:
- int base_id;
- string base_name;
- };
- ////////////////////////////////////////////////////
- class Derived : public Base
- {
- public:
- //constructor
- Derived(int num=0, string str="", int val=0):
- Base(num, str), derived_id(val){
- cout<<"Derived construction"<<endl;
- }
-
- //Destructor
- virtual ~Derived(){
- cout<<"Derived destroyed\n";
- }
-
- virtual void print(){
- cout<<"derived id = "<<derived_id<<endl;
- }
-
- //Derived class必須實作來自Base class的abstract method
- //否則在程式中class無法被implementation
- void printall(){
- cout<<"hello world"<<endl;
- }
-
- protected:
- int derived_id;
- };
- ////////////////////////////////////////////////////
- int main()
- {
- Base *ptr = new Derived(1, "derived", 2);
-
- ptr->print(); //call Derived print()
- ptr->printall();
- delete ptr;
-
- return EXIT_SUCCESS;
- }
- 在建構Derived class時,會先呼叫Base class的constructor,再呼叫Derived class的constructor,而destroy object時是相反的方向。
- 當Base class的method全部為abstract method時,可將Base class視為Java的interface來使用。