我正在编写一个程序来测试具体的继承,尽管我无法解决Clang返回的重复符号链接器错误。我的理解是,重复的符号总是不正确的包含/保护的结果。我已经三次检查了我的包含/保护,但没有发现任何错误。重复的符号可能是包含保护之外的其他原因造成的吗?非常感谢,随着我编程技能的提高,我打算经常在这里做出贡献。
.h
#ifndef POINTARRAY_H
#define POINTARRAY_H
#include "array.h"
namespace Jules
{
namespace Containers
{
class PointArray: public Array<Point>
{
public:
PointArray(); //default constructor
~PointArray(); //destructor
PointArray(const PointArray& p); //copy constructor
PointArray(const int i); //constructor with input argument
PointArray& operator = (const PointArray& source); //assignment operator
double Length() const; //length between points in array
};
}
}
#ifndef POINTARRAY_CPP
#include "PointArray.cpp"
#endif
#endif
.cpp
#ifndef POINTARRAY_CPP
#define POINTARRAY_CPP
#include "PointArray.h"
using namespace Jules::CAD;
namespace Jules
{
namespace Containers
{
PointArray::PointArray() : Array<Point>() //default constructor
{
}
PointArray::~PointArray() //destructor
{
}
PointArray::PointArray(const PointArray& p) : Array<Point>(p) //copy constructor
{
}
PointArray::PointArray(const int i) : Array<Point>(i) //constructor with input argument
{
}
PointArray& PointArray::operator = (const PointArray& source) //assignment operator
{
if (this == &source)
return *this;
PointArray::operator = (source);
return *this;
}
double PointArray::Length() const
{
double lengthOfPoints = 0;
for (int i = 0; i < Array::Size()-1; i++)
lengthOfPoints += (*this)[i].Distance((*this)[i+1]);
return lengthOfPoints;
}
}
}
#endif
更新:感谢大家的帮助。我现在懂力学了。
不要在头中包含cpp
文件。如果你这样做,每个包含你的头的翻译单元最终都会有一个类的定义,例如PointArray
,这会导致多个定义的链接器错误。
将其从页眉中删除。
#ifndef POINTARRAY_CPP
#include "PointArray.cpp"
#endif
#endif
您在.h
中对.cpp
文件进行#include
处理,这将导致.cpp
代码包含在使用.h
的每个文件中(因此会出现重复符号)。您还滥用了include保护:只有头文件需要include保护;.cpp
文件不应该有它们。