C++之Virtual初探(一)

小弟季義欽發表於2012-11-02
#include<iostream>
using namespace std;

class A{
public:
	virtual ~A(){f();}
	virtual void f(){cout<<"This is A virtual"<<endl;}
	void g(){cout<<"This is A no-virtual"<<endl;}
};

class B:public A{
public:
	~B(){f();}
	virtual void f(){cout<<"This is B virtual"<<endl;}
	void g(){cout<<"This is B no-virtual"<<endl;}
};

int main(){
	//如果是virtual方法的話,和Java中多型現象一樣
	A* p = new B;
	p->f();	
	A* q = new A;
	q->f();

	//如果不是virtual方法,那麼只看引用是什麼型別
	A* w = new A;
	w->g();
	A* x = new B;
	x->g();	
	
	cout<<"====delete all object!==="<<endl;
	delete p;
	delete q;
	delete w;
	delete x;
	return 0;
}

再看一個例子:

#include <iostream>
using namespace std;

class Base{  
public:  
    Base(int j) : i(j) {}   
    virtual ~Base() {}  
    void func1(){  
		cout<<"Base func1"<<endl;
        i *= 10;
		//但是Base的func2是virtual,所以要看真正的物件是什麼型別
		//如果是Child型別物件,那麼就應該呼叫Child的func2函式
        func2();  
    }  
    int getValue(){  
        return i;  
    }  
protected:  
    virtual void func2(){  
        i++;
		cout<<"Base func2"<<endl;
    }  
protected:  
    int i;  
};  
  
class Child : public Base {  
public:  
    Child(int j) : Base(j) {}  
    void func1(){  
		cout<<"Child func1"<<endl;
        i *= 100;  
        func2();  
    }  
protected:  
    void func2(){  
        i += 2;
		cout<<"Child func2"<<endl;
    }  
};  
  
int main(void){  
    Base *pb = new Child(1);  
    pb->func1(); //func1不是虛擬函式,所以這裡引用是Base型別,就呼叫Base的func1函式  
    cout<<pb->getValue()<<endl;  
    delete pb;  
      
    return 0;  
}  


相關文章