gpt4 book ai didi

带有模板编译错误的 C++ 类

转载 作者:太空狗 更新时间:2023-10-29 23:38:17 25 4
gpt4 key购买 nike

我不是经验丰富的 C++ 程序员,而且我在编译时遇到了问题。我有一个使用模板的堆类:

template <class T>
class Heap
{
public:
Heap(const vector<T>& values);

private:
vector<T> d;

// etc.
};

然后在单独的实现文件中:

template <class T>
Heap<T>::Heap(const vector<T>& values)
{
d = values;

for (unsigned int i = d.size()-1; i > 0; i--) Heapify(ParentIndex(i));
}

// ... more implementation code ...

最后是一个 main.cc 文件:

int main (int argc, char *argv[])
{
vector<int> in;
unsigned int i;

while (cin >> i) in.push_back(i);
Heap<int> h = Heap<int>(in);

return 0;
}

我得到这些编译错误:

g++ -Wall -I/opt/local/include -c -o main.o main.cc
g++ -Wall -I/opt/local/include -c -o heap.o heap.cc
g++ -Wall -o heap main.o heap.o
Undefined symbols:
"Heap<int>::Heap(std::vector<int, std::allocator<int> > const&)", referenced from:
_main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [heap] Error 1

为什么不能编译?我认为链接器说它找不到构造函数,但我知道它生成了目标文件。

最佳答案

模板需要 100% 在头文件中定义。如果您有 Heap<T>在 .cc/.cpp 文件中实现就是问题所在。将所有代码移至头文件,它应该可以解决您的问题。

关于带有模板编译错误的 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1631398/

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