polymorphism error: redefinition of a pointer (C++)

polymorphism error: redefinition of a pointer (C++)

我已经收录了

#ifndef FileName_H
#define FileName_H
...
#endif

在我所有的头文件中。在我的 main.cpp 中,我想使用 class Worker:

的多态性
Worker * w = NULL;
w = new Employee(001,"Tom",3);
w->showInfo();
delete w;

Worker * w = NULL;
w = new Manager(002,"Bob",1);
w->showInfo();
delete w;

Worker * w = NULL;
w = new Boss(003,"Ann",2);
w->showInfo();
delete w;

然而,error: redefinition of 'w'总是会发生。我包含了 #ifndef 语句,我删除了指针并将其设置为 NULL,然后再重新使用它。我不知道为什么仍然会出现此错误。你能给我一些可能的原因或线索吗?

正是错误信息所说的。

Worker * w = NULL;
w = new Employee(001,"Tom",3);
w->showInfo();
delete w;

Worker * w = NULL; // <<<<<<< here's the problem 
w = new Manager(002,"Bob",1);
w->showInfo();
delete w;

对指针的第二次赋值重新定义了指针变量,这在同一范围内是不允许的。 您的代码应该如下所示:

Worker * w = NULL;
w = new Employee(001,"Tom",3);
w->showInfo();
delete w;

w = new Manager(002,"Bob",1); // No type declaration!
w->showInfo();
delete w;