简体   繁体   English

C ++,多重继承和dynamic_cast

[英]C++, multiple inheritance and dynamic_cast

I'm new with programming with objects, and i'm learning by myself RTTI in c++, i googled about it and found a lot of examples of RTTI using animal class and mammal class, using virtual functions and dynamic_cast, so i decided to give a try to see how it works, so i wrote a little program. 我对对象编程不熟悉,我正在用C ++自己学习RTTI,我在Google上搜索了一下,发现了很多使用动物类和哺乳动物类,使用虚拟函数和dynamic_cast的RTTI示例,所以我决定给出尝试看看它是如何工作的,所以我写了一个小程序。 Here is the code: 这是代码:

#include <iostream>
#include<string>
#include<cstdlib>

using namespace std;

class animal 
{
public:
   virtual void print()const   // Virtual print function
   {  cout << "Unknown animal type.\n";
   }
   virtual ~animal(){} // Virtual destructor, discussed below
protected:
   int nlegs;
   string animaltype;
};

class bird: public animal 
{
protected:
  string name;
public:
   bird(int n, string c, string nom){nlegs = n; animaltype = c; name = nom;}
   void print()const
   {  cout << "A " << animaltype << " has " << nlegs << " legs.\n";
   }
};

class eagle : public bird
{
public:
  eagle(int n, string c, string nom)
  {
     nlegs = n;
     clase = c;
     nombre = nom;
  }
};

int main()
{  
   int count = 1;
   animal* p[count];
   int i;
   p[0] = new bird(2,"bird","eagle");

   bird* b = new bird(2,"bird","chicken")
   for (i=0; i<count; ++i) 
   {
       b = dynamic_cast<bird*>(p[i]);
   }
   for (i=0; i<count; ++i) 
       delete p[i];
 }

When i try to compile it marks some errors, but one error says "eje2a.cpp: In constructor 'eagle::eagle(int, std::string, std::string)': eje2a.cpp:53:3: error: no matching function for call to 'bird::bird()'" 当我尝试编译时,它标志着一些错误,但是一个错误表明“ eje2a.cpp:在构造函数中,'eagle :: eagle(int,std :: string,std :: string)':eje2a.cpp:53:3:error :没有匹配的函数来调用'bird :: bird()'“

What does this error refers to? 此错误指的是什么? do i need to create a new function named bird or is other thing that i'm missing to declare? 我需要创建一个名为bird的新函数还是我想声明的其他东西吗?

I would greatly appreciate your help. 非常感谢您的帮助。

Thanks in advance 提前致谢

eagle does not explicitly call any bird constructor, so the default constructor is choosen (which does not exist due to your own constructor with arguments). eagle不会显式调用任何bird构造函数,因此将选择默认构造函数(由于您自己带有参数的构造函数,因此不存在)。 You may fix your code with: 您可以使用以下方式修复代码:

eagle(int n, string c, string nom)
    : bird(n, c, nom)
{
}

This : bird syntax is an initializer list, in which you can call the base classes and the members constructors (within the constructor body, they're already initialized and you can only assign values to them). : bird语法是一个初始化程序列表,您可以在其中调用基类和成员构造函数(在构造函数主体内,它们已经被初始化,您只能为其分配值)。

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

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