编译时重新定义错误

时间:2018-04-16 04:45:15

标签: c++ class

我一直在搜索其他论坛和问题,但我似乎无法找到与我的问题相关的答案。我在.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

Shape.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;
}

1 个答案:

答案 0 :(得分:1)

我一直收到这样的错误,说明&#34;重新定义&#39;形状&#39;&#34;在.cpp文件中?没有Shape.cpp只定义一次,只是确保两者都是不同的文件。评论低于//#include <iostream> /* already included in shape.h */ #include "Shape.h" //using namespace std; /* already there in shape.h */

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

你可能需要像下面那样打电话

@import url('cdn-url.css')

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