gpt4 book ai didi

c++ - 错误 : redefinition of class

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:50:42 26 4
gpt4 key购买 nike

这是我的代码:

// 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( header )和 .cpp 文件(实现)之间构建您的代码。

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

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

针对此错误的额外保护是 Include Guards , 或头部保护。

大多数编译器都支持类似 #pragma once 的内容,您可以在 .h 文件的顶部编写这些内容,以确保只编译一次。

如果 pragma 不适用于您的编译器,则可以使用传统的 Include/Header 保护系统:

#ifndef MYHEADEFILE_H
#define MYHEADEFILE_H

// content of the header file

#endif

关于c++ - 错误 : redefinition of class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26179408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com