class Base
{
public:
virtual void display(const std::string& strShow = "I am Base class !")
{
std::cout << strShow << std::endl;
}
virtual ~Base(){}
};
class Derive: public Base
{
public:
virtual void display(const std::string& strShow = "I am Derive class !")
{
std::cout << strShow << std::endl;
}
virtual ~Derive(){}
};
int main()
{
Base* pBase = new Derive();
Derive* pDerive = new Derive();
pBase->display();
pDerive->display();
delete pBase;
delete pDerive;
return 0;
};
分析程序的输出结果。为什么?
【参考答案】缺省参数是静态绑定的。pBase 和 pDerive 调用display时实际都执行的是Derive类的display,但是pBase 是使用了基类的缺省参数值。所以输出:
I am Base class !
I am Derive class !