出现此类错误的原因是出现了多重包含头文件的问题。应该在main.cpp源文件中只包含派生类的头文件即可,而不应该把基类的头文件包含进来。因为我们在派生类的头文件中已经对基类的头文件进行了包含。
例如,下面的例子。
有两个头文件,基类为shape.h,派生类为rectangle.h。以及对应的实现文件shape.cpp和rectangle.cpp和主函数源文件main.cpp。
//shape.h
#include<iostream>
using namespace std;
//基类
class Shape
{
public:
void setWidth(int);
void setHeight(int);
protected:
int width;
int height;
};
//rectangle.h,在定义派生类时包含基类头文件
#include"shape.h"
class Rectangle:public Shape
{
public:
int getArea();
};
//shape.cpp
#include"shape.h"
void Shape::setWidth(int w)
{
width=w;
}
void Shape::setHeight(int h)
{
height=h;
}
//rectangle.cpp
#include"rectangle.h"
int Rectangle::getArea()
{
return(height*width);
}
//main.cpp
//在主函数源文件中只需包含派生类的头文件即可
#include"shape.h"
#include"rectangle.h"
int main()
{
Rectangle rec;
rec.setHeight(5);
rec.setWidth(6);
cout<<"Total Area:"<<rec.getArea()<<endl;
return 0;
}