C++、多重继承和 dynamic_cast

标签 c++

我是对象编程的新手,我正在用 C++ 自学 RTTI,我在谷歌上搜索了一下,发现了很多使用动物类和哺乳动物类、使用虚函数和 dynamic_cast 的 RTTI 示例,所以我决定尝试看看它是如何工作的,所以我写了一个小程序。这是代码:

#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];
 }

当我尝试编译时,它标记了一些错误,但一个错误是“eje2a.cpp: In constructor 'eagle::eagle(int, std::string, std::string)': eje2a.cpp:53:3: 错误:没有匹配函数来调用 'bird::bird()'"

这个错误指的是什么?我需要创建一个名为 bird 的新函数还是我缺少声明的其他内容?

非常感谢您的帮助。

提前致谢

最佳答案

eagle 没有显式调用任何 bird 构造函数,因此选择了默认构造函数(由于您自己的带参数的构造函数,它不存在)。您可以使用以下方法修复您的代码:

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

这个 : bird 语法是一个初始化列表,你可以在其中调用基类和成员构造函数(在构造函数体内,它们已经被初始化,你只能为它们赋值).

关于C++、多重继承和 dynamic_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25909119/

相关文章:

c++ - 除了使用 inotify 之外如何递归监视目录

c++ - 我可以将 multimap 迭代逻辑放到另一个函数中吗?

c++ - C++ 中的复合类型、const 和 auto

c++ - 为 Levenberg-Marquardt 算法构建 Mex 时出错 - 表示存在的目录不存在

c++ - boost::interprocess 共享内存 : how to have multiple different shared memory on same machine

c++ - 我将如何使用大小运算符 delete/delete[] 以及为什么它们更好?

c++ - OpenCV:findHomography 生成一个空矩阵

c++ - 如果指针设置为 NULL,则任何对它的引用或通过它的引用也不会是 NULL

c++ - 如何解释 kcachegrind 的结果

java - 此代码始终返回图像未加载,路径是否正确。这是 android NDK 中的 opencv