如何区分派生类的对象C ++ [英] How to distinguish objects of derived classes 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
是基类. B
和C
是派生类.我想设置一个向量来保存B
或C
,并使用向量a
来保存A
.但是,由于a
是包含A
对象的向量,因此我无法访问B
和C
中的方法.反正有什么办法可以使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
,导致<存储B
或C
时,em>对象切片.特别是,这意味着当您存储B
时,仅会存储aa
; bb
被切开.
Your vector of A
is not capable of holding B
s or C
s, 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.
如果不进行强制转换,这将无助您访问特定于B
或C
的功能.解决此问题的一种方法是将C
的功能提供给A
,并通过B
的A
类型引用进行调用>或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屋!