2014-10-03 91 views
2

这里是我的代码:错误:类重新定义

// 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' 

我该如何解决这个问题?

+0

退房“包括卫士”或'的#pragma once'用于支持类似的东西编译器。它看起来像标题可能会包含多次。整个包括cpp文件...这通常不是如何完成的。 – Niall 2014-10-03 13:03:23

回答

8

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

你应该包括头文件:.h 永远不要包括.cpp文件。 (除非你知道你在做什么,而且那将是非常罕见的情况)。

否则你结束编译几次你的类,你会得到你的编译器告诉你错误:“类的重新定义......”

+0

为什么不呢? .......... – 2014-10-03 13:01:51

+0

因为否则你多次编译类,你会得到编译器告诉你的错误:重新定义类。 – 2014-10-03 13:03:17

+0

@AvivCohn糟糕的做法,类似你的错误等。请参阅http://www.cplusplus.com/forum/general/39618/ – matsjoyce 2014-10-03 13:04:13

9

你的main.cpp中包含的文件,其中包括shape.cpp,最终被包含多次。您可以通过一个定义的检查包裹你的包含文件避免这种情况:

#ifndef SHAPE_CPP 
#define SHAPE_CPP 

//file contents 

#endif 
+1

为什么downvote?除了包含cpp文件是一种不好的做法,这其实有什么错? – 2014-10-03 13:05:08