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

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

按照传统的思维,类的声明定义在.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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值