虚函数如何工作,分配后新的返回类型会发生什么?
how virtual functions work and what happens to new return type when assigned?
#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 类型的对象中找到指向虚函数的指针。
相关文章:
- 返回类型在 C++ OOP 中是什么意思
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- T*&返回类型到底是什么
- 虚函数如何工作,分配后新的返回类型会发生什么?
- 运算符和返回类型是什么意思?
- 作为返回类型"const int&"做什么?
- STD :: SETW,STD :: SETFILL等的真实返回类型是什么?
- const 在具有尾随返回类型的自动退货声明中是什么意思
- C++协方差返回类型的缺点是什么
- 尾随返回类型中的占位符类型的用途是什么
- 从具有引用返回类型的函数返回什么
- C++中以下函数的返回类型是什么
- 此函数的返回类型是什么
- 提升的返回类型是什么::apply_visitor(延迟版本)
- C 中构造函数的返回类型是什么
- T const & 在函数的返回类型中是什么意思?
- 作为返回类型的枚举关键字的存在表明什么
- 什么是布尔维纳皮返回类型
- 如果返回了向量的一个项,lambda表达式的返回类型是什么
- 当函数返回值是指针,而返回类型是c++中的引用时会发生什么