fout: herdefinitie van klasse

Hier is mijn code:

// 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;
};

Tijdens het compileren krijg ik deze foutmelding:

error: redefinition of 'class Shape'

Hoe kan ik dit oplossen?


Antwoord 1, autoriteit 100%

U moet uw code structureren tussen .h (headers) en .cpp-bestanden (implementatie).

U moet header-bestanden opnemen: .h
Voeg nooit .cpp-bestanden toe. (Tenzij je weet wat je doet, en dat zou in zeer zeldzame gevallen zijn).

Anders beëindig je het compileren van je klasse meerdere keren, en krijg je de foutmelding die je compiler je vertelt: ‘redefinition of class…’

Een extra bescherming tegen deze fout zijn Include Guardsof Header Guards.

De meeste compilers ondersteunen iets van het soort #pragma oncedat je bovenaan de .h-bestanden schrijft om ervoor te zorgen dat het maar één keer wordt gecompileerd.

Als het pragma niet beschikbaar is voor uw compiler, dan is er het traditionele Include/Header guard-systeem:

#ifndef MYHEADEFILE_H
#define MYHEADEFILE_H
// content of the header file
#endif

Antwoord 2, autoriteit 94%

Uw main.cpp bevat bestanden met shape.cpp, die uiteindelijk meerdere keren worden opgenomen. U kunt dit voorkomen door uw opgenomen bestanden te verpakken met een vinkje voor een definitie:

#ifndef SHAPE_CPP
#define SHAPE_CPP
//file contents
#endif

Other episodes