编译时重定义错误:.cpp文件中'Shape'重定义问题求助
Hey there, let's break down why you're hitting that annoying "Redefinition of 'Shape'" error and how to fix it. This is super common with C++ header file setups, so let's go through the most likely culprits step by step.
1. Incomplete Header Guard
Looking at the partial Shape.h code you shared, you started with the header guard (#ifndef SHAPE_H / #define SHAPE_H) but it looks like the code got truncated—did you forget to add the closing #endif at the end of the header file?
If the header guard isn't closed, every time your .cpp file (or other files) include Shape.h, the entire class definition gets reprocessed, leading to duplicate definitions.
Fixed Shape.h Example
Here's what your complete header should look like (I also added the missing <string> include since you're using std::string):
#ifndef SHAPE_H #define SHAPE_H #include <iostream> #include <string> // Critical for using std::string 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
2. Duplicate Definitions in .cpp File
Another common issue: if you accidentally redefined the Shape class or its member functions in your .cpp file. For example:
- Don't write
class Shape {...}again in the.cpp—you only need to define the member functions using the scope resolution operator (::). - Don't implement non-inline functions both in the header and the
.cpp. If you wroteShape() {}directly in the header, then tried to defineShape::Shape()in the.cpp, that's a redefinition.
Correct .cpp Implementation Example
Here's how your Shape.cpp should look to avoid conflicts:
#include "Shape.h" // Default constructor Shape::Shape() : name("Unknown") {} // Parameterized constructor Shape::Shape(string name) : name(name) {} // Getter function string Shape::getName() const { return name; } // Overloaded << operator ostream& operator << (ostream& output, const Shape& shape) { output << "Shape Name: " << shape.name; return output; }
3. Duplicate Class Definitions Across Files
Double-check if you have another .h or .cpp file in your project that also defines a class Shape. Even a duplicate empty definition will cause a redefinition error during linking.
Quick Additional Tips
- Avoid defining non-inline functions directly in headers (unless you mark them
inline). Each file that includes the header will generate a copy of the function, leading to link-time conflicts. - Make sure you're only including
Shape.hin your.cppfiles with#include "Shape.h"(not<Shape.h>—that's for system headers).
内容的提问来源于stack exchange,提问作者amanhasnoname

