【发布时间】:2014-09-23 12:00:05
【问题描述】:
header.h
#include <iostream>
using namespace std;
class A
{
public:
virtual void display(int i=5) { cout<< "Base::" << i << endl; }
};
class B : public A
{
public:
void display(int i=9) { cout<< "Derived::" << i << endl; }
};
source.h
#include <iostream>
#include "header.h"
using namespace std;
int main()
{
A * a = new B();
a->display();
A* aa = new A();
aa->display();
B* bb = new B();
bb->display();
}
输出
Derived::5
Base::5
Derived::9
我的理解是在编译时使用函数重载解决了默认参数函数。然后在运行时使用函数覆盖来解析虚函数。
但是发生的事情是一团糟。
这里的函数解析实际上是如何发生的?
【问题讨论】:
-
Default argument resolution is based on the static type of the object through which you call the function(即基于指针类型)。 social.msdn.microsoft.com/Forums/en-US/… -
请注意,您可以通过使用另一个不带参数的虚拟函数重载虚拟函数来解决此问题,该虚拟函数“转发”到带有参数的虚拟函数。喜欢:在 Base
virtual void display() { display(9); }和 Derivedvoid display() { display(5); }
标签: c++ virtual-functions overload-resolution