C++ 错误:重新定义类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26179408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:32:56  来源:igfitidea点击:

error: redefinition of class

c++compiler-errors

提问by Aviv Cohn

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?

我怎样才能解决这个问题?

回答by James Thorpe

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:

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

#ifndef SHAPE_CPP
#define SHAPE_CPP

//file contents

#endif

回答by Stephane Rolland

You should structure your code between .h (headers) and .cpp files (implementation).

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

You should include header files: .hNever include .cppfiles. (Unless you know what you do, and that would be in really rare cases).

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

Otherwise you're ending compiling several times your class, and you get the error your compiler is telling you: 'redefinition of class...'

否则,您将多次结束类的编译,并且您会收到编译器告诉您的错误:“重新定义类...”