Avi*_*ohn 5 c++ compiler-errors
这是我的代码:
// 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;
};
Run Code Online (Sandbox Code Playgroud)
编译时,我收到此错误:
error: redefinition of 'class Shape'
Run Code Online (Sandbox Code Playgroud)
我怎样才能解决这个问题?
Ste*_*and 12
您应该在.h(标题)和.cpp文件(实现)之间构建代码.
您应该包含头文件:.h
从不包含.cpp
文件.(除非你知道你做了什么,而且这种情况非常罕见).
否则你将结束几次类的编译,并且你得到编译器告诉你的错误:'重新定义类......'
Jam*_*rpe 12
你的main.cpp包含的文件包括shape.cpp,最终被包含多次.您可以通过检查定义来包装包含的文件来避免这种情况:
#ifndef SHAPE_CPP
#define SHAPE_CPP
//file contents
#endif
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26585 次 |
最近记录: |