我是对象编程的新手,我正在用 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/