基类派生类实虚函数

#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

posted @ 2020-03-18 20:53  cloudren2020  阅读(259)  评论(0编辑  收藏  举报