C++ 大师。
我正在尝试在 C++ 中实现多态性。我想编写一个带有虚函数的基类,然后在子类中重新定义该函数。然后在我的驱动程序中演示动态绑定。但我就是无法让它工作。
我知道如何在 C# 中做到这一点,所以我想我可能在我的 C++ 代码中使用 C# 的语法时犯了一些语法错误,但这些错误对我来说一点也不明显。因此,如果您能纠正我的错误,我将不胜感激。
#ifndef POLYTEST_H
#define POLYTEST_H
class polyTest
{
public:
polyTest();
virtual void type();
virtual ~polyTest();
};
#endif
#include "polyTest.h"
#include <iostream>
using namespace std;
void polyTest::type()
{
cout << "first gen";
}
#ifndef POLYCHILD_H
#define POLYCHILD_H
#include "polyTest.h"
using namespace std;
class polyChild: public polyTest
{
public:
void type();
};
#endif
#include "polyChild.h"
#include <iostream>
void polyChild::type()
{
cout << "second gen";
}
#include <iostream>
#include "polyChild.h"
#include "polyTest.h"
int main()
{
polyTest * ptr1;
polyTest * ptr2;
ptr1 = new polyTest();
ptr2 = new polyChild();
ptr1 -> type();
ptr2 -> type();
return 0;
}
我意识到我没有实现构造函数或析构函数,因为这只是一个测试类,它们不需要做任何事情,编译器会提供一个默认的构造函数/析构函数。这就是我收到编译错误的原因吗?为什么会这样?