我从一本书上读了一些代码,像这样:
#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);
}
};
关于c++ - 为什么子类重写虚函数不能改变父类默认函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28826246/