C++虚函数

b_a*_*n_a 0 c++ polymorphism virtual-functions

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;
}
Run Code Online (Sandbox Code Playgroud)

我意识到我没有实现构造函数或析构函数,因为这只是一个测试类,它们不需要做任何事情,并且编译器将提供默认的构造函数/析构函数.这就是我收到编译错误的原因吗?那为什么会这样呢?

jua*_*nza 6

你的指针应该是基类型:

polyTest * ptr1;
polyTest * ptr2;
Run Code Online (Sandbox Code Playgroud)

polyChild 是-A polyTest,但是polyTest不是一个polyChild.