"Multiple definition of.." "First defined here"数据结构中的同一行中

"Multiple definition of.." "First defined here" in the same line in a data structure

本文关键字:一行 数据结构 definition Multiple of First defined here      更新时间:2023-10-16

在发表这篇文章之前,我已经读了很多文章,我找不到一个解决方案,因为它们(我读的那些)都不是关于数据结构的。

我有两个数据结构(如果重要的话,堆和UF)。
它们都在.h文件中实现。我得到的是"多重定义…"首先定义在这里"错误仅在类外实现的成员函数(如int UnionFind::Find(int i))
对于c'和d'也会发生,但当我在类中实现它们时,它就消失了。我真的不知道为什么会这样。
我在所有文件中都遵循了include,并且没有双重include或循环。

我也使用AVL树,它不会发生在那里,一切都是在类之外的。h文件中实现的。

这些是我得到的错误:

/tmp/ccp8fP73.o: In function `UnionFind::Find(int)':
main.cpp:(.text+0x0): multiple definition of `UnionFind::Find(int)'
/tmp/ccVxSiPy.o:Elections.cpp:(.text+0x0): first defined here
/tmp/ccp8fP73.o: In function `UnionFind::Union(int, int)':
main.cpp:(.text+0x108): multiple definition of `UnionFind::Union(int, int)'
/tmp/ccVxSiPy.o:Elections.cpp:(.text+0x108): first defined here
如果你需要更多的信息,请告诉我。谢谢你

如果我理解正确的话,你在做这样的事情:

// C.h
class C
{
   void f(); // declaration of f; ok to include in many modules
};
// definition of f; must not exist in more than one module
void C::f()
{
}

这不起作用,因为f()的定义将在包含C.h的每个模块中结束,导致您描述的链接器错误。您可以通过将f()标记为inline或将f()的定义移动到单独的cpp文件中来解决此问题。

有一种特殊情况是允许的,那就是当f()是模板时(直接或因为C是模板)。在这种情况下,定义必须位于头文件中,这样编译器就可以知道如何为您指定的任何类型实例化它。这确实使链接器的生活变得困难,因为您可以并且经常以通常是错误的各种冗余定义结束(例如,如果您在多个模块中使用f<int>())。需要特殊的行为来处理这个

顺便说一下,当你把函数体移到类定义内部时,事情之所以有效,是因为这有使它们隐式内联的效果。

如果你想手工创建模板..

//1。包含模板代码..

#include <template/list.tmpl.c>

//2。实例化使用它的实例.

#include "/c/viewer/src/ViewObject.h"
#include "/c/viewer/src/WindowAdaptor.h"
template class List<ViewObject>;
template class List<WindowAdaptor>;