Here's my 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;
};
When compiling, I get this error:
error: redefinition of 'class Shape'
How can I fix this?
You should structure your code between .h (headers) and .cpp files (implementation).
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.
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
Your main.cpp includes files which include shape.cpp, which ends up being included multiple times. You can avoid this by wrapping your included files with a check for a definition:
#ifndef SHAPE_CPP
#define SHAPE_CPP
//file contents
#endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With