gpt4 book ai didi

c++ - 模板类构造函数中的动态分配

转载 作者:行者123 更新时间:2023-11-30 02:03:03 25 4
gpt4 key购买 nike

我正在处理堆栈类并且有两个构造函数。感兴趣的是这个。

template <typename T>
stack<T>::stack( const int n)
{
capacity = n ;
size = 0 ;
arr = new T [capacity] ;
}

我在 main 中这样调用它。

stack<int> s1(3) ;

程序编译正常,但出现运行时错误。

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall
stack<int>::~stack<int>(void)" (??1?$stack@H@@QAE@XZ) referenced in function _main

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall
stack<int>::stack<int>(int)" (??0?$stack@H@@QAE@H@Z) referenced in function _main

1>D:\\Microsoft Visual Studio 10.0\Visual Studio 2010\Projects\Expression
Evaluation\Debug\Expression Evaluation.exe : fatal error LNK1120: 2 unresolved externals

我正在处理 Microsoft visual studio 2010,这个问题让我无处可去。任何提示将不胜感激。

最佳答案

这不是运行时错误,而是链接器错误。问题可能是构造函数和析构函数的实现在源文件中。对于模板类,您必须将所有方法的实现放在 header 中(或在使用它们的源文件中,但这等同于将它们放在 header 中)。

所以基本上是这样做的:

template<class T>
class stack
{
public:
stack( const int n)
{
capacity = n ;
size = 0 ;
arr = new T [capacity] ;
}

// and the same for all other method implementations
};

关于c++ - 模板类构造函数中的动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12540928/

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