简体   繁体   English

C ++子类与它们自己的类型及其父类是否相同?

[英]C++ Are child classes of the same type as themselves AND their parent class?

After a semester without C++ but plenty of Java i now i have a lot of new questions. 一个学期没有C ++但有大量Java之后,我现在有很多新问题。

Given class baseClass and class childClass : public baseClass definitions and, let's say, the instances baseClass bClass(); childClass cClass(); 给定class baseClassclass childClass : public baseClass定义,以及实例baseClass bClass(); childClass cClass(); baseClass bClass(); childClass cClass(); , in a Java equivalent context (though in C++) would cClass instanceof bClass be true ? ,在Java等效上下文中(尽管在C ++中), cClass instanceof bClasstrue

And, if so(now on polymorphism), would a function add(baseClass &left, baseClass &right) be able to expect ANY of the baseClass 's children as the left and/or right ? 并且,如果是这样(现在是多态性的话),函数add(baseClass &left, baseClass &right)是否可以期望baseClass的子级中的任何一个作为left和/或right

I supose the last question may be misleading, but it still depends on the first one being true, so if needed i'll expand more on that afterwards. 我认为最后一个问题可能会引起误解,但这仍然取决于第一个问题是否正确,因此,如果需要,我将在此之后进一步扩展。

Thank you! 谢谢!

would cClass instanceof bClass be true? cClass instanceof bClass是否为真?

Yes

would a function add(baseClass &left, baseClass &right) be able to expect ANY of the baseClass's children as the left and/or right? 函数add(baseClass&left,baseClass&right)是否可以期望baseClass的任何子级作为左和/或右?

Yes. 是。 This is called upcasting (because you are moving up the hierarchy) and is the concept behind runtime polymorphism in C++. 这称为upcasting (因为您正在向上移动层次结构),并且是C ++中运行时多态性背后的概念。 Consider the example below 考虑下面的例子

class A
{
public:
  func()
  {
    cout << "A";
  }
};

class B : public A
{
public:
  func()
  {
    cout << "B";
  }
};

void foo(A &obj)
{
  obj.func();
}

int main()
{
  A a;
  B b;

  foo(a);

  cout << endl;

  foo(b);

  return 0;
}

Output: 输出:

A 
B

We can safely supply reference to child class object to a function expecting a reference to base class object because whatever exists in base class will exist in child class. 我们可以安全地向期望引用基类对象的函数提供对子类对象的引用,因为基类中存在的任何内容都将存在于子类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM