虚函数如何工作,分配后新的返回类型会发生什么?

how virtual functions work and what happens to new return type when assigned?

本文关键字:返回类型 什么 分配 何工作 函数 工作      更新时间:2023-10-16
#include<iostream>
using namespace std;
class Father
{
public:
int a=99;
void MakeAThing(){ cout<<"MakeAThing of father called"<<endl;}
virtual void MakeAThing2(){ cout<<"MakeAThing2 of father called"<<endl;}
};
class Child : public Father
{
public:
int b=11;
void MakeAThing(){ cout<<"MakeAThing of child called"<<endl;}
virtual void MakeAThing2(){ cout<<"MakeAThing2 of child called"<<endl;}
};
int main(){
Father *obj;
obj = new Child();
obj->MakeAThing();// MakeAThing of Father is called
//code to find out if  obj becomes a Child* after new
Father fa  
fa=*obj;
cout <<fa.b<<endl; // error: 'Class Father' has no member 'b'
//which means fa remains an object of Class Father

Father *obj2;
obj2 = new Child();
obj2->MakeAThing2();// MakeAThing2 of Child is called
return 1;
}

有人可以解释一下主要发生了什么吗? 我的尝试:

obj 是指向 Father 类型的对象的指针

obj= new Child();new为Child类型的对象分配内存并返回指向void的指针:*void,对吗?,那么obj是转换为*void类型还是仍然是*Father类型? 为什么?

obj->MakeAThing();《父亲的制造》中被称为,为什么?

obj2->MakeAThing2();为什么关键字 virtual 使调用 MakeAThing2 指的是孩子而不是父亲?

两个指针的静态类型都是Father *

Father *obj;
Father *obj2;

因此,当您尝试调用成员函数时,编译器将在类 father 中搜索其声明。

因此,在此声明中

obj->MakeAThing();

有所谓的类父亲的成员函数。

在此通话中

obj2->MakeAThing2();

编译器将调用类 Child 中定义的重写虚函数,因为使用指向虚函数的指针表调用函数。由于指针的动态类型Child *则编译器将在 Child 类型的对象中找到指向虚函数的指针。