Chinaunix首页 | 论坛 | 博客
  • 博客访问: 51580
  • 博文数量: 6
  • 博客积分: 165
  • 博客等级: 入伍新兵
  • 技术积分: 72
  • 用 户 组: 普通用户
  • 注册时间: 2006-08-18 16:19
文章分类

全部博文(6)

文章存档

2012年(3)

2011年(1)

2009年(1)

2006年(1)

我的朋友

分类: C/C++

2012-04-18 21:50:18

今天在CDT下用C++模板碰到一个很古怪的问题,基本情况就是在模板类里定义了操作符友员函数,
但这种情况下编译器无法确定该函数是否在模板范围类. 样例代码如下:

点击(此处)折叠或打开

  1. #include <iostream>

  2. using namespace std;

  3. template<class T>
  4. class LinearList {
  5. public:
  6.     LinearList(int MaxListSize = 10);
  7.     ~LinearList() {delete [] element;}
  8.     LinearList<T>& Delete(int k, T& x);
  9.     LinearList<T>& Insert(int k, const T& x);
  10.     void Output(ostream& out) const;
  11.     friend ostream& operator<< (ostream& os, const LinearList<T>& other);

  12. private:
  13.     int length;
  14.     int MaxSize;
  15.     T *element;
  16. };


这里[]对该问题要详细的描述,提供了两个解决办法:
i) 在模板类定义之前声明friend函数,同时把<>添加到friend函数名称后,具体修改如下:

点击(此处)折叠或打开

  1. template<class T> class LinearList; # 由于friend中要引用该模板类,故需在此提前声明
  2. template<class T>
  3. ostream& operator<< (ostream& os, const LinearList<T>& other);

  4. template<class T>
  5. class LinearList {
  6. ...
  7.     friend ostream& operator<< <> (ostream& os, const LinearList<T>& other);

  8. };

ii) 在friend声明的地方加上实现,这个修改就比较简单:

点击(此处)折叠或打开

  1. template<class T>
  2. class LinearList {
  3. public:
  4.     friend ostream& operator<< (ostream& os, const LinearList<T>& other)
  5.     {
  6.       ...
  7.     }
  8. };


阅读(1682) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~