编译时出现重定义错误

Redefinition error at compile time

本文关键字:定义 错误 编译      更新时间:2023-10-16

我一直在搜索其他论坛和问题,但我似乎找不到与我的问题相关的答案。我不断收到此错误,在.cpp文件中显示"重新定义'形状'",并且它同时出现在构造函数和函数中。

形状.h

#ifndef SHAPE_H
#define SHAPE_H
#include <iostream>
using namespace std;

class Shape {
private:
    string name;
public:
    Shape();
    Shape(string name);
    string getName() const;
    friend ostream& operator << (ostream& output, const Shape & shape);
};
#endif // SHAPE_H

形状.cpp

#include <iostream>
#include "Shape.h"
using namespace std;
Shape::Shape() {
    this->name = "Shape";
}
Shape::Shape(string name) {
    this->name = name;
}
string Shape::getName() const {
    return name;
}
ostream& operator << (ostream& output, const Shape & shape) {
    output << shape.getName();
    return output;
}

我不断收到此错误,在.cpp文件中显示"重新定义'形状'">?没有Shape只定义一次,只需确保两者都是不同的文件。以及 2 行下方的评论 Shape.cpp

//#include <iostream> /* already included in shape.h */
#include "Shape.h"
//using namespace std; /* already there in shape.h */

您可能需要像下面这样打电话

int main() {
        Shape obj("Nick Morin");
        using std::cout<<obj;
        return 0;
}

阅读这篇文章 为什么"使用命名空间 std"被认为是不好的做法?