当在C ++中给出指向基类的指针时,为什么不调用派生类对象的重载函数? [英] Why is not overloaded function for derived class object invoked when given a pointer to base class in C++?
问题描述
在以下代码中
#include <iostream>
using namespace std;
class A {
public:
A() {}
virtual ~A() {};
};
class B : public A {
public:
B() {}
virtual ~B() {};
};
void process(const A&) {
cout << "processing A" << endl;
}
void process(const B&) {
cout << "processing B" << endl;
}
int main(void) {
A* a = new B;
process(*a);
return 0;
}
运行它的输出变为
processing A
但我会假设应该是
processing B
因为 a
指向派生类 B
而不是 A
。那么为什么它会调用 process
函数的第一个实现而不是第二个?
since a
points to the derived class B
and not A
. So why does it call the first implementation of process
function and not the second?
推荐答案
静态类型表达式 * a
是 A
因为 a
被宣布为
The static type of expression *a
is A
because a
was declared as
A* a = new B;
编译器使用参数的静态类型解析重载函数的选择。
The compiler resolves the selection of overloaded functions using the static type of the argument.
即使调用虚函数,编译器也会使用对象的静态类型来调用适当的函数。不同之处仅在于编译器使用指向虚函数的指针表来间接调用所需的函数。
Even when virtual functions are called the compiler uses the static type of the object to call appropriate function. The difference is only that the compiler uses the table of pointers to virtual functions to indirectly call the required function.
这篇关于当在C ++中给出指向基类的指针时,为什么不调用派生类对象的重载函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!