虚拟函数查找的规则是什么? [英] What are the rules for virtual function lookup?
问题描述
#include <iostream>
class base
{
public:
virtual void print (int a)
{
std::cout << "a: " << a << " base\n";
}
virtual void print (int a, int b)
{
std::cout << "base\n";
}
};
class derived : public base
{
public:
virtual void print (double d)
{
std::cout << "derived\n";
}
};
int main ()
{
int i = 10;
double d = 10000.0;
base *b = new derived ();
b->print (i, i);
b->print (d);
return 0;
}
此函数的输出为:
base
a: 10000 base
- 为什么
b->print (d)
不调用派生类的实现,并且 对'd'
执行静态强制转换以提供与基类的匹配 实施? - 在查找虚拟函数期间在此处应用什么规则?
- Why
b->print (d)
don't invoke the derived class implementation and performs static cast on'd'
to provide a match with base class implementation ? - What rule is applied here during virtual function lookup ?
推荐答案
derived::print
不会覆盖base
中的任何成员函数.它被声明为具有单个double
类型的参数,但是在base
中被命名为print
的两个虚拟成员函数被声明为具有一个和两个类型为int
的参数.
derived::print
does not override any member function in base
. It is declared as having a single parameter of type double
but the two virtual member functions named print
in base
are declared as having one and two parameters of type int
.
使用b->print(d)
时,在重载解析期间仅考虑base
中的成员函数,因此仅考虑void base::print(int)
和void base::print(int, int)
.找不到void derived::print(double)
,因为编译器不知道b
指向derived
对象.
When you use b->print(d)
, only member functions in base
are considered during overload resolution, so only void base::print(int)
and void base::print(int, int)
are considered. void derived::print(double)
can't be found because the compiler has no idea that b
points to a derived
object.
如果derived
要覆盖在base
中声明为虚拟成员函数的两个print
函数之一,则该覆盖将在运行时被调用.
If derived
were to override one of the two print
functions declared as virtual member functions in base
, then that override would be called at runtime.
(有点相关的注释,derived::print
隐藏了两个base::print
成员函数,因此,如果您尝试使用基类print
函数之一,例如derived().print(1, 1)
,它将失败.您将需要使用using声明,以使这些成员函数在名称查找期间可用.)
(On a somewhat related note, derived::print
hides the two base::print
member functions, so if you were to try to use one of the base class print
functions, e.g., derived().print(1, 1)
, it would fail. You would need to use a using declaration to make those member functions available during name lookup.)
这篇关于虚拟函数查找的规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!