【问题标题】:Redefinition error at compile time编译时重定义错误
【发布时间】:2018-04-16 04:45:14
【问题描述】:

我一直在搜索其他论坛和问题,但似乎找不到与我的问题相关的答案。我不断收到这个错误,在 .cpp 文件中显示“重新定义 'Shape'”,它出现在构造函数和函数中。

形状.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;
}

【问题讨论】:

  • 无法重现,因此我们需要更多信息。将using namespace std; 放入标题时要非常小心。对于没有预料到的人来说,这可能是一个非常令人讨厌的惊喜。
  • 听起来这段代码工作正常。
  • 我的教授给了我这个代码来开始一个项目,但我没有接触过它,所以我很困惑为什么它会给我这些错误。如果我还有更多工作要做,我会把它给你。
  • 你有main()吗?你包括"shape.h" 还是"shape.cpp"

标签: c++ class


【解决方案1】:

我在 .cpp 文件中不断收到“重新定义‘形状’”的错误?没有Shape 只定义一次,只需确保两者都是不同的文件。以及来自Shape.cpp的2行以下的cmets

//#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;
}

阅读这篇文章Why is "using namespace std" considered bad practice?

【讨论】:

  • 是你提到的两个 cmets 导致了这个问题。我没有意识到这样的事情会影响它。
  • @nick_eagles 如果没有其他问题,这些都不应该有任何影响。两个文件中的#include &lt;iostream&gt; 不应该有任何影响。标头保护防止多个包含。多个using namespace stds 也没有效果。 The damage is already done.
  • 两次包含标题不是问题。我同意你@user4581301
  • 是的,我认为这不是问题,但它现在正在编译,所以我没有抱怨。感谢大家的帮助,很抱歉浪费了宝贵的编码时间。
  • 嘿@nick_eagles,这是你的时间,不是我的。如果我现在有更重要的事情要做,我可能会不去做。或者睡觉。这里已经很晚了。
猜你喜欢
  • 1970-01-01
  • 2016-07-13
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多