多态指针的typeid?

typeid for polymorphic pointers?(多态指针的typeid?)
本文介绍了多态指针的typeid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么指针不是多态类型,因为我们可以使用指向派生类的基类指针来调用派生类的虚函数.这表明在运行时,系统可以确定指针是否是多态的,不是吗?

I don't understand why pointers aren't polymorphic types, since we can use base class pointers, which are pointing to derived classes, to call derived class' virtual function. This suggests at runtime, the system can determine if a pointer is polymorphic, doesn't it?

(这是来自typeid for polymorphic types的后续问题)

(This is a follow-up question from typeid for polymorphic types)

推荐答案

您的问题是因为术语使用不正确.C++ 语言在指针本身和这些指针指向的对象之间做出了非常明确的区分.指针类型不是多态的.指针本身没有任何多态性.真正可以多态的是指针指向的类型.当指针指向多态类型时,我们通常 [非正式地] 称其为多态指针(只是指向多态类型的指针"的简写).但是当涉及到 typeid 之类的东西时,他们会非常正式地看待事物.对于 typeid,指针类型永远不会是多态的.

Your question suffers from incorrect usage of terminology. C++ language makes a very clear distinction between pointers themselves and objects these pointers point to. Pointer types are not polymorphic. There's nothing polymorphic about the pointer itself. What can really be polymorphic is the type the pointer points to. When a pointer points to a polymorphic type, we often [informally] call it polymorphic pointer (just as a shorthand for "a pointer that points to a polymorphic type"). But when it comes to things like typeid, they see things very formally. For typeid pointer types are never polymorphic.

并且编译器不会在运行时确定指针是否是多态的.这种简单的区别总是在编译时立即知道.同样,如果将指针声明为指向多态类型的指针,则该指针称为多态.多态类型是包含虚函数(直接或间接)的类类型.显然,多态性是一个类型的纯编译时属性.

And the compiler does not determine whether the pointer is polymorphic or not at run-time. This simple distinction is always immediately known at compile-time. Again, a pointer is referred to as polymorphic if it is declared as a pointer to polymorphic type. Polymorphic type is a class type that contains virtual functions (directly or indirectly). Obviously, the property of being polymorphic is a purely compile-time property of a type.

在这种情况下,在运行时唯一确定的是在给定时刻指向的对象具有哪种特定类型.

The only thing that is determined at run-time in such cases case is which specific type the pointed object has at the given moment.

这篇关于多态指针的typeid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Polymorphic copy-constructor with type conversion(具有类型转换的多态复制构造函数)
Cast to a Child(铸造给孩子)
How to use virtual functions to achieve a polymorphic behavior in C++?(如何使用虚函数在 C++ 中实现多态行为?)
Polymorphism is not working with function return values of same data type (Base and Inherited class)(多态性不适用于相同数据类型(基类和继承类)的函数返回值)
Size of class with virtual function adds extra 4 bytes(具有虚函数的类的大小增加了额外的 4 个字节)
Right design pattern to deal with polymorphic collections of objects(正确的设计模式来处理对象的多态集合)