错误:重新定义类

时间:2014-10-03 12:59:49

标签: 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;
};

编译时,我收到此错误:

error: redefinition of 'class Shape'

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:11)

您的main.cpp包含的文件包含shape.cpp,最终会被多次包含。您可以通过检查定义包装所包含的文件来避免这种情况:

#ifndef SHAPE_CPP
#define SHAPE_CPP

//file contents

#endif

答案 1 :(得分:9)

您应该在.h(标题)和.cpp文件(实现)之间构建代码。

您应该包含标头文件:.h 永远不要包含.cpp个文件。 (除非你知道你做了什么,而且这种情况非常罕见)。

否则,您将结束几次类的编译,并且您得到编译器告诉您的错误:&#39;重新定义类...&#39;