C++premier
先看例子吧
#include"iostream"
using namespace std;
class base{
public:virtual int foo(int ival=1024){
cout<<"base::foo()--ival:"<<ival<<endl;
return ival;
}
};
class derived:public base{
public:int foo(int ival=2048){
cout<<"derived::foo()--ival:"<<endl;
return ival;
}
};
int main()
{
derived *pd=new derived;
base *pb=pd;
int val =pb->foo();
cout<<"main():val through base:"<<val<<endl;
val=pd->foo();
cout<<"main():val through derived:"
<<val<<endl;
}
我是初学C++,用编译器运行突然发现输出的是
好像有点不对啊,从结果derived::foo()--ival都是调用了derived里的foo,符合多态的机制,但是问题是1024和2048怎么回事呢?
书上是这么解释的,供大家参考:
调用的真正函数是在运行时刻pb和pd指向的类型所决定,也就是晚捆绑,而缺省实参是在编译时刻就根据被调用函数的对象的类型所决定。具体解释可见C++ PREMIER page771.第三版哦。