gpt4 book ai didi

包含模板类的C++编译程序

转载 作者:行者123 更新时间:2023-11-28 01:13:58 25 4
gpt4 key购买 nike

<分区>

我遇到了一些编译问题,这里是详细信息:

假设我声明了一些数据结构 my_data_struct<typename T> .我在这里使用模板的原因是我希望我的数据结构能够处理任何数据类型(像 std::stackstd::vector 一样)

在那种情况下,如果我不知道它将用于的最终类型,我必须在一个文件中定义和声明我的结构。

让我们说,我还有几个其他库(除以 .h 声明和 .cpp 定义)。他们每个人都使用 my_data_struc .

最后,假设我有 main.cpp #include 的“全部”文件的。

我怎样才能编译我的程序?

如果我将我的 cpp 文件单独编译为目标文件,并尝试将它们链接在一起,我将收到 multiple definition of错误,因为 my_data_struct将被定义几次...

我意识到的唯一方法是将我的库的定义移动到它的声明 ( .h ) 文件中,然后只编译 main.cpp一次全部。但是,这样编译程序是正确的方法吗?或者有没有更好的方法来构建和编译这些东西?

我没有找到任何关于如何继续它的最佳实践......

谢谢指教。

更新:

好吧,在创建示例时,我发现实际问题不是由模板类引起的,而是由同一命名空间中类旁边存在的非模板函数引起的:

//mydatastruct.h
#ifndef MYSTRUCT
#define MYSTRUCT

namespace G{
template<typename T>
class my_data_struct{
public:
my_data_struct(){};
~my_data_struct(){};
int do_something(int a){ return a; };
//...
};

int test(int b){ return 2; };
}

#endif
// a.h
#ifndef A_H
#define A_H

#include "mydatastruct.h"

class A{
public:
A();
~A();
};

#endif

// a.cpp
#include "a.h"
A::A(){}
A::~A(){}
// main.cpp
#include "a.h"
int main(){ return 0; }

编译:

g++ -c a.cpp -o a.o
g++ -c main.cpp -o main.o
g++ a.o main.o -o main.exe

实际错误是:

main.o:main.cpp:(.text+0x0): multiple definition of `G::test(int)'
a.o:a.cpp:(.text+0x0): first defined here

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com