错误:重新定义班级 [英] error: redefinition of class
问题描述
这是我的代码:
// in main.cpp
#include "iostream"
#include "circle.cpp"
#include "rectangle.cpp"
#include "shape.cpp"
using namespace std;
int main() {
Shape shapes[10];
for (int i = 0; i < 10; i++){
if (i % 2)
shapes[i] = Circle(5);
else
shapes[i] = Rectangle(10, 10);
cout << shapes[i].getArea();
}
return 0;
}
// in circle.cpp
#include "shape.cpp"
class Circle : public Shape {
private:
int radius;
static const double PI = 3.14159265358979323846;
public:
Circle (int radius) : radius(radius) {}
virtual int getArea() const {
return PI * radius*radius;
};
virtual int setRadius(int radius){
radius = radius;
}
};
// in rectangle.cpp
#include "shape.cpp"
class Rectangle : public Shape {
private:
int width;
int height;
public:
Rectangle(int width, int height) : width(width), height(height){}
virtual int getArea() const {
return width * height;
}
virtual void setWidth(int width){
this->width = width;
}
virtual void setHeigth(int height){
this->height = height;
}
};
// in shape.cpp
class Shape {
public:
virtual int getArea() const = 0;
};
编译时出现此错误:
error: redefinition of 'class Shape'
如何我可以解决这个问题吗?
How can I fix this?
推荐答案
您应该在.h(标题)和.cpp文件(实现)之间构造代码。
You should structure your code between .h (headers) and .cpp files (implementation).
您应包含头文件: .h
切勿包含 .cpp
文件。 (除非您知道您要做什么,否则在极少数情况下会发生这种情况。)
You should include header files: .h
Never include .cpp
files. (Unless you know what you do, and that would be in really rare cases).
否则,您将结束几次类的编译,并且会收到编译器告诉您的错误:类的重新定义...
Otherwise you're ending compiling several times your class, and you get the error your compiler is telling you: 'redefinition of class...'
针对此错误的另一种保护措施是包括警卫队或标头警卫队。
An additional protection against this error are Include Guards, or Header Guards.
大多数编译器都支持类似 #pragma一次
写在 .h
文件的顶部,以确保仅被编译一次。
Most compilers support something of the like #pragma once
that you write at the top of .h
files to ensure it is compiled only once.
如果编译器不适用于编译器,然后是传统的包含/标头保护系统:
If the pragma is not available for your compiler, then there is the traditionnal Include/Header guard system:
#ifndef MYHEADEFILE_H
#define MYHEADEFILE_H
// content of the header file
#endif
这篇关于错误:重新定义班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!