【发布时间】: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 的新函数还是我缺少要声明的其他东西?
非常感谢您的帮助。
提前致谢
【问题讨论】:
-
为bird添加默认构造函数
标签: c++