一个小练习题,猜猜结果:
#include<iostream>
using namespace std;
enum HEIGHT{
LOW=150,
MID=160,
HIGH=170
};
class Person{
public:
virtual void printHeight(int h=LOW){
cout<<"h in Person="<<h<<endl;
}
};
class Man: public Person{
public:
virtual void printHeight(int h=HIGH) override{
cout<<"h in Man="<<h<<endl;
}
};
int main(){
Man m;
m.printHeight(); //h in Man=170
Person *p = &m;
p->printHeight(); //h in Man=150
}
结果已经在代码注释中。
好像《effective c++》有过解释,标准也有如下话语(也可参考)Default arguments - cppreference.com:
A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides.
意思是:我们知道虚函数调用是动态决定的,但默认参数是静态(编译期)决定的 。哪到底怎么静态决定的哪?默认参数又是怎么传参的哪?调出汇编看一看:
0xaa就是170,0x96就是150,就是这么直接给传了进去。
大多数人都有个疑问,为啥不像虚函数那样动态决定默认参数?stackoverflow上有同样的问题,如有兴趣请参数c++ - static binding of default parameter - Stack Overflow
大概意思就是实现起来复杂。可能也不值得,把责任丢给了开发者。