C++模板类编写需要注意的一点

来源:互联网 发布:怎么在淘宝网开网店 编辑:程序博客网 时间:2024/05/22 10:28

今天,写一个简单的队列实现的程序,利用模板。

按照传统的思维,类的声明定义在.h文件中,模板类成员函数的实现在.cpp文件中。但是编译的时候没问题,但是链接的时候不能链接到模板函数而出错。

这个问题的主要原因在于模板在主函数里实例化的时候,调用模板类函数,但是又找不到模板的原型,从而导致出错。这一点是模板区别于传统的编程方式。

所以这个问题的解决方法就是把模板类函数的实现和类的声明放在同一个.h文件内,这样就不会出现链接的错误了。

接下来是另外一个问题。模板中友元的声明。

首先是非模板的函数或者类:

template< class type > class fruit{       friend  class vegetables;       friend  void fcn(const type& eat);......}
上面的vegetables类与fcn函数均可访问模板类的成员。

接下来,看下模板的友元声明:

template< class type > class fruit{       template <class T> friend  class vegetables;       template <class A> friend  void fcn(const A&);......}

以上一般通常的声明方法如下:

template <class T>  class vegetables;template <class A>  void fcn(const A&);template< class type > class fruit{       friend  class vegetables<type>;       friend  void fcn<type>(const type&);......}

有时候,我们不想一个模板的友元都能够获取访问权限,只想其中的几个类别能够获取访问权限,可以这样声明:

template <class T>  class vegetables;template <class A>  void fcn(const A&);template< class type > class fruit{       friend  class vegetables<int>;       friend  void fcn<char*>(const char*);......}

0 0