如何区分派生类的对象C ++ [英] How to distinguish objects of derived classes C++

查看:111
本文介绍了如何区分派生类的对象C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看下面的代码:

class A
{
protected:
    int aa = 1;
};

class B : public A
{
private:
    int bb = 2;
public:
    int getbb() { return bb; }
};

class C : public A
{
private:
    int cc = 3;
public:
    int getcc() { return cc; }
};

int main()
{
    std::vector<A> a;
    B b;
    C c;
    a.push_back(b);
    a.push_back(c);

    a[0].getbb(); //getbb() unaccessible;
    a[1].getcc(); //getcc() unaccessible;
}

A是基类. BC是派生类.我想设置一个向量来保存BC,并使用向量a来保存A.但是,由于a是包含A对象的向量,因此我无法访问BC中的方法.反正有什么办法可以使a[0].getbb()a[1].getcc()工作?

A is the based class. B and C is the derived classes. I want to set a vector to hold either B or C, and use vector a to hold A. However, since a is a vector containing A's objects, I can't access methods in B and C. Is there anyway to make a[0].getbb() and a[1].getcc() work?

推荐答案

您的A向量不能容纳B s或C s,因为它按值存储A,导致<存储BC时,em>对象切片.特别是,这意味着当您存储B时,仅会存储aabb被切开.

Your vector of A is not capable of holding Bs or Cs, because it stores A by value, resulting in object slicing when B or C is stored. In particular, this means that when you store B, only aa gets stored; bb gets sliced away.

为了存储子类而不进行切片,请使用一个指针容器-最好是 smart 指针.

In order to store subclasses without slicing use a container of pointers - preferably, of smart pointers.

如果不进行强制转换,这将无助您访问特定于BC的功能.解决此问题的一种方法是将>的 virtual 成员函数和C的功能提供给A,并通过BA类型引用进行调用>或C.

This wouldn't help you access functionality specific to B or C without a cast. One way to solve this problem is to give virtual member functions for B's and C's functionality to A, and make calls through A-typed reference of B or C.

这篇关于如何区分派生类的对象C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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