【问题标题】:C++, multiple inheritance and dynamic_castC++、多重继承和dynamic_cast
【发布时间】:2014-09-18 09:35:21
【问题描述】:

我是使用对象编程的新手,我正在自学 C++ 中的 RTTI,我在 Google 上搜索了一下,发现了很多使用动物类和哺乳动物类、使用虚函数和 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 的新函数还是我缺少要声明的其他东西?

非常感谢您的帮助。

提前致谢

【问题讨论】:

标签: c++


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多