模板类构造函数中的动态分配 [英] Dynamic Allocation in Template Class Constructor

查看:189
本文介绍了模板类构造函数中的动态分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个堆栈类和有两个构造函数。一个感兴趣的是这一个。

I am working on a stack class and have two constructors. One of interest is this one.

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

我在main里面调用它。

I am calling it inside main like this.

stack<int> s1(3) ;

程序编译正常,但我得到此运行时错误。

The program compiles fine but i get this run time error.

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 ,这个问题无处不在。

I am working on Microsoft visual studio 2010 and this problem is taking me nowhere. Any hint would be appreciated.

推荐答案

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

It's not a runtime error, it's a linker error. The problem is probably that the implementations of the constructor and the destructor are in a source file. With template classes, you have to place the implementations of all the methods in the header (or in the source file that uses them, but that's equivalent to putting them in the 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
};

这篇关于模板类构造函数中的动态分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆