您的位置:程序门 -> c/c++ -> c++ 语言



c++类模板的问题,构造函数老是不行。


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


c++类模板的问题,构造函数老是不行。[已结贴,结贴人:silendream]
发表于:2008-01-19 21:13:29 楼主
这是我写的一个容器的小例子,刚一开头就出现了问题。我实在是找不出问题到底出在哪   但是老是出错
我用的是vc2008
下面是错误提示:
main.obj   :   error   lnk2019:   unresolved   external   symbol   "public:   __thiscall   myctn <int> ::myctn <int> (int)"   (??0?   $myctn@h@@qae@h@z)   referenced   in   function   _main

c/c++ code
#include "iostream" template <typename type> class myctn { public: myctn( const myctn<type> & ); // 赋值构造 myctn( int size = defsize ); // 自定义容器大小 ~myctn(){delete [] items;} type& operator [] ( int ) ; // 赋值 type operator [] ( int ) const ; // 取数 private: enum { defsize = 10 }; int ctnsize; int ctnlength; type* items; }; template <typename type> myctn<type>::myctn(int size):ctnsize(size) { items = new type [size]; ctnlength = 0; } template <typename type> myctn<type>::myctn(const myctn<type> & ctn) { ctnsize = ctn.ctnsize; items = new type [ctn.ctnsize]; ctnlength = ctn.ctnlength; forint i=0; i<ctn.ctnlength; i++ ) items[i] = ctn.items[i]; } template <typename type> type& myctn<type>::operator [](int num) { if ( num >= ctnsize || num < 0) { std::cout<<num<<" it is out of limit !"<<std::endl; std::exit (exit_failure); } return *(items+num); } template <typename type> type myctn<type>::operator [](int num) const { if ( num >= ctnsize || num < 0 ) { std::cout<<num<<" it is out of limit !"<<std::endl; std::exit (exit_failure); } return *(items+num); } void main() { using std::cout; myctn<int> aaa(5); // 构造通过不了。 }
发表于:2008-01-19 21:23:141楼 得分:0
items                 =   new   type   [size];

貌似数组不能动态设置大小,是不是这个错了??
发表于:2008-01-19 21:25:302楼 得分:3
俺记错了。。。
发表于:2008-01-19 21:26:553楼 得分:2
没问题啊。可以通过编译,运行。
发表于:2008-01-19 21:32:024楼 得分:3
唉没装vc2008的,
咱这只有6.0和05的盘,
看样子帮不了你了,
不过在6.0里可以运行,
结果直接为“press   any   key   to   continue   ”
发表于:2008-01-19 21:32:085楼 得分:2
是不是头文件忘记包含了?
发表于:2008-01-19 21:36:446楼 得分:2
一切正常~~
发表于:2008-01-19 22:05:547楼 得分:0
谢谢各位     ~~
恩   可是谁能帮我解释一下这个错误的提示是什么意思么??
发表于:2008-01-19 22:18:578楼 得分:5
链接错误2019,main   里面调用了未声明的外部符号public:       __thiscall       myctn   <int>   ::myctn   <int>   (int)"      
发表于:2008-01-19 22:19:369楼 得分:0
记得给分啊楼主,活活。。
发表于:2008-01-19 22:44:1410楼 得分:3
把声明部分的
c/c++ code
myctn( const myctn<type> & );

改成
c/c++ code
myctn( const myctn& );

试试

定义部分就不用改了
发表于:2008-01-19 22:53:4711楼 得分:0
你只要那么改,我几乎可以肯定能ok
发表于:2008-01-20 12:17:4912楼 得分:0
谢谢各位     问题我找到了。
原来是模板类的成员函数不能在一个单独的文件里定义。
要和声明写在同一个头文件里才行。
谢谢各位


快速检索

最新资讯
热门点击