了解堆栈上分配的实例的C ++虚拟方法 [英] Understanding C++ Virtual Methods of Instances Allocated on the Stack
本文介绍了了解堆栈上分配的实例的C ++虚拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于以下代码:
#include<iostream>
using namespace std;
class A{
public:
virtual int f(){return 1;}
};
class B : public A{
public:
virtual int f(){return 2;}
};
int main(int argc,char*argv[]){
A b=B();
cout<<b.f()<<endl;
}
我希望数字 2
。而是程序打印的数字 1
I expect the number 2
to be printed. Instead the program prints the number 1
.
有人可以解释为什么是这样?
Could someone explain why this is?
推荐答案
您所做的是称为切片。请参阅 C ++中的切片问题是什么?
What you've done is called slicing. See What is the slicing problem in C++?
应使用:
A* b = new B();
这篇关于了解堆栈上分配的实例的C ++虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文