c++ - 将基类的引用分配给派生
问题描述
我不太清楚如何以及为什么可以给出WhatType()
Derived1 和 Derived2 类型的函数参数,以及为什么输出是:
ob is referencing an object of type 4Base
ob is referencing an object of type 8Derived1
ob is referencing an object of type 8Derived2
#include <iostream>
#include <typeinfo>
using namespace std;
class Base {public: virtual void f () { } };
class Derived1: public Base { };
class Derived2: public Base { };
void WhatType(Base &ob){
cout << "ob is referencing an object of type " << typeid(ob).name() << endl;}
int main() {
Base b;
Derived1 d1;
Derived2 d2;
WhatType(b);
WhatType(d1);
WhatType(d2);
return 0;
}
我想我以前见过这种类型的“问题”并且记住了它是如何发生的,但我想有一些严格的解释。
解决方案
推荐阅读
- javascript - 在功能组件中需要图像 - Nuxt/Vue
- sql - 如果存在则选择使用 WHERE,否则不要使用 WHERE
- java - 如何将 TIFF 文件列表传递给 TessAPI1.TessBaseAPIProcessPages
- neo4j - 如何在一个查询中获取与节点相关的边数 - NEO4J
- c++ - 如何在 Arduino C++ (FastLED) 的另一个类中使用一个类?
- c# - 如何记录传出的 HttpClient 请求?
- apache-spark - 如何根据 Spark DataFrame 中的 B 列获取 A 列的 5 条记录
- python - 如何通过忽略初始列标题来获得正确的 Dataframe 架构?
- python - python计算字符串列表中的单词数
- reactjs - 请求在 createError 处失败,状态码为 404