首页 > 代码库 > C++虚函数的默认参数问题

C++虚函数的默认参数问题

#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;

class Base
{
public:
	Base(int i):m_num(i)
	{
		cout<<"Base Constructor"<<endl;
	}
	virtual ~Base()
	{
		cout<<"Base Deconstructor"<<endl;
	}

	virtual void func(int num=-100)
	{
		cout<<num<<endl;
		cout<<"This is Base class"<<endl;
	}
private:
	int m_num;
};

class Derived:public Base
{
public:
	Derived():Base(10)
	{
		cout<<"Derived constructor"<<endl;
	}
	~Derived()
	{
		cout<<"Derived deconstructor"<<endl;
	}
	void func(int num=100)
	{
		cout<<num<<endl;
		cout<<"This is Derived class"<<endl;
	}
};


int main()
{
	{
		Base* pb=new Derived();
		cout<<"-------------------------"<<endl;
		pb->func();
		cout<<"-------------------------"<<endl;
		Derived* pd=dynamic_cast<Derived*>(pb);
		pd->func();
		cout<<"-------------------------"<<endl;

		delete pb;
	}

	system("pause");
	return 0;
}

总结:

虚函数的默认参数,与调用该虚函数的指针类型对应