基類派生類實虛函數

#include <iostream>
using namespace std;

class Base
{
protected:
	int x;
public:
	Base(int n):x(n){}
	void display(){
		cout << __FUNCTION__ << " Base: " << x << endl;
	}
	virtual void display2(){
		cout << __FUNCTION__  << " Base: " << x << endl;
	}
};

class Derived: public Base
{
	int y;
public:
	Derived(int m):Base(m),y(m){}
	void display(){
		cout << "Derived: " << y << endl;
	}
	virtual void display2(){
		cout << __FUNCTION__  << " Derived: " << x << endl;
	}

};


int main(void)
{
	Derived d(2);
	Base * p = &d;
	cout << "實函數測試:\n";
	p->display();
	cout << "虛函數測試:\n";
	p->display2();
	return 0;
}

實函數測試:
display Base: 2
虛函數測試:
display2 Derived: 2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章