虚拟继承/多态性
Virtual inheritance / Polymorphism
所以我正在研究一些奇怪的多食症和多义性。有一个案例我无法理解。我不明白为什么下面代码的最后一行会这样。
#include <stdio.h>
#include <iostream>
class Article
{
public :
virtual bool compare(Article *a) { std::cout << "ACA" << std::endl;}; // ACA
};
class Clothe : public Article
{
public :
bool compare (Clothe *c) { std::cout << "CCC" << std::endl;}; // CCC
bool compare (Article *a) { std::cout << "CCA" << std::endl;}; // CCA
};
int main()
{
Article *pta1 = new Article;
Article *pta2 = new Clothe;
Clothe *ptv1 = new Clothe;
pta1->compare(pta2); // print ACA
pta2->compare(pta1); // print CCA
pta2->compare(pta2); // print CCA because compiler needs to explore pta2 to determine which compare to use.
// pta2 is instanced as a Clothe, so one of Clothe's compare will be called.
// And judging by its declaration pta2 is an Article (even thought it's instanced as a Clothe),
// so it will Call Clothe::Compare(Article*). I'm OK with this
pta2->compare(ptv1); // print CCA ??? WHY , pta2 is explored, thus it's type is determined to be of type Clothe.
// And ptv1 is declared as a Clothe, so it should call Clothe::compare(Clothe* c)
// should print CCC, shouldn't it ?
}
我迷路了。我不明白 g++ 如何以这种方式解决歧义。任何帮助/解释都会很好。感谢您的阅读,更感谢那些回答的人。
PS :我知道比较应该返回布尔值,但这在这里并不重要。
编辑:在我即时翻译变量名称的过程中,错别字滑了,名称最初是法语的,对此感到抱歉。现已修复
此行
pta2->compare(ptv1);
打印CCA
,因为基类中只有一个虚函数bool compare(Article *a)
。
你对pta2
的假设是错误的。
探索 pta2,因此将其类型确定为 Clothe 类型。
事实并非如此。pta2
的类型是Article *
的,仅此而已。它只指向一个Clothe
对象,因此可以通过它调用Clothe
函数,如果(并且仅当)它们在派生类中存在并且是虚拟的,并且是基类并被覆盖(使用相同的签名!
简单来说:
如果调用是通过基类指针执行的,则编译器只能在派生类中"查找"重载,这些重载在基类中存在且是虚拟的。
这里发生了什么:
pta2
是指向Article
的指针。因此,在调用compare
时,会考虑Article
中compare
函数的不同可能性。唯一的匹配是
bool Article::compare (Article *a)
.现在,编译器发现
compare
Article
是虚拟的,并使用一些内部机制通过对象的"vtable"进行虚拟调用。当
Clothe
覆盖bool compare (Article *a)
时,被覆盖的函数被调用。
基类对bool compare (Clothe *c)
一无所知,因为它对Clothe
一无所知,因此输出不CCV
。
- 继承/多态性 - 我是否被迫使用"protected"变量?
- 具有 3 级继承的基类shared_ptr的多态性
- C 中的多态性.在基类上调用继承的方法
- 模板、继承和多态性 C++
- 了解C++中的继承和多态性
- 继承多态性功能调用
- C++接口、继承、多态性
- 如何在保持多态性的同时,将成员函数添加到需要它的继承类中,而不会影响其他同级类?
- 在C++中使用多态性相对于继承的实际优势
- 收到未定义的引用错误 c++ 继承/多态性
- 多态性(继承)和价值类型
- 多种继承和多态性问题
- 如何正确组织继承类以利用多态性
- C++ 继承和多态性未知输出
- '<<'与继承和多态性超载?
- 在继承层次结构中将方法定义为虚拟方法一次,以使多态性发挥作用
- c++:多态性+多重继承顺序.继承顺序是否重要
- C++多重继承多态性
- 虚类成员函数的多态性/继承问题
- C++ 多态性 - 继承类的映射