首页 > 解决方案 > 将基类的引用分配给派生

问题描述

我不太清楚如何以及为什么可以给出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;
}


我想我以前见过这种类型的“问题”并且记住了它是如何发生的,但我想有一些严格的解释。

标签: c++inheritancereferencepolymorphism

解决方案


推荐阅读