在c ++中进行对象切片的可能解决方法是什么? [英] What is a possible workaround for object slicing in c++?

查看:66
本文介绍了在c ++中进行对象切片的可能解决方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

#include <string>
#include <vector>
#include <iostream>
using namespace std;
class A {
public:
  virtual const string f() const { return "A"; }
};
class B : public A {
public:
  const string f() const { return "B"; }
};
int main(int ac, char** av) {
  vector<A> v;
  v.push_back(B());
  cout << v.at(0).f() << endl;
  return 0;
}

预期结果为 B ,但它是 A 。据我了解,对象切片正在进行中。如何避免呢?我应该将指针存储在 vector 而不是对象实例中吗?

Expected result is B, but it's A. As I understand object slicing is taking place. How to avoid it? Shall I store pointers in vector instead of object instances? Is this the only choice?

推荐答案

您需要存储指针。如果这些引用是动态分配的对象,请使用智能指针

You need to store pointers. If these refer to dynamically allocated objects, use smart pointers.

这篇关于在c ++中进行对象切片的可能解决方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆