我读过一本书中的一些代码,比如:
#include<iostream>
using namespace std;
class Father
{
public:
virtual void test(int value=520)
{
cout<<"father:"<<value<<endl;
}
};
class Son :public Father
{
public:
virtual void test(int value=250)
{
cout<<"son:"<<value<<endl;
}
};
int main()
{
Son* son =new Son;
son->test();
Father* fson= son;
fson->test();
}
程序输出:
son250
son520
书中说,虚拟函数的默认参数是在编译时确定的。
我的问题是:虚拟函数的默认参数为什么不在运行时决定?就像虚拟函数本身。
C和C++的制作者不想让事情复杂化。实现在编译时解析的默认参数很简单,而在运行时则不那么简单。但是,您可以也应该使用一种变通方法。引入一个没有参数的虚拟函数,而不是使用默认参数。
class Father
{
public:
virtual void test(int value)
{
cout << "father:" << value << endl;
}
virtual void test()
{
test(520);
}
};
class Son : public Father
{
public:
virtual void test(int value)
{
cout << "son:" << value << endl;
}
virtual void test()
{
test(250);
}
};