加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 错误:重新定义类

发布时间:2020-12-16 10:44:17 所属栏目:百科 来源:网络整理
导读:这是我的代码: // 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
这是我的代码:

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

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

解决方法

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

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

否则你将结束几次类的编译,并且你得到编译器告诉你的错误:’重新定义类……’

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读