| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 568 人关注过本帖
标题:探讨类模板下的操作符重载的实例化
只看楼主 加入收藏
lizecn
Rank: 1
等 级:新手上路
帖 子:8
专家分:0
注 册:2006-3-23
收藏
 问题点数:0 回复次数:2 
探讨类模板下的操作符重载的实例化

请大人指教我一下, 为什么我的操作符不能多类型实例化,
以下的程序很简单, 是个队列的链表表示方法, 用<<来添加,
用>> 来删除, 用重载的<<来显示队列.
目前的问题是不能
同时实例化两种类型的队列(int 和double), 经过跟踪分析,
如果把操作符重载全部注释, 可以实例化两种类型的队列,
所以问题可能出现在操作符重载, 希望高手明示一下.
运行结果是: 打印一个int类型的队列(1-11).

#include <iostream>
#define taillemax 20
using namespace std;

template <class T>
class ElementCase{
public:
T Data;
public:
ElementCase<T> *Next;
ElementCase(T &n):Data(n),Next(NULL){}


};

template <class T>
class File{
public: ElementCase<T> *head;
ElementCase<T> *tail;
int size;
File<T>():size(0){} //修改的地方
bool IsEmpty();
bool IsFull();
T Remove();
void Reset();
void operator<<(T &n);
void operator>>(T &n);
template <class Type>
friend void operator<<(ostream &s, File<T> &f);

};

template <class T>
bool File<T>::IsEmpty(){
if (size==0) return true;
else return false;
}

template <class T>
bool File<T>::IsFull(){
if (size==taillemax) return true;
else return false;
}

template <class T>
void File<T>::operator<<(T &n){
ElementCase<T> *p;
p=new ElementCase<T>(n);
if(size==0){
head=p;
tail=p;
size=1;
return;
}
if(!IsFull()){
tail->Next=p;
tail=p;
size+=1;
}
else cout<<"Pleine"<<endl;
}

template <class T>
T File<T>::Remove(){
if(IsEmpty()){
cout<<"Vide"<<endl;
return 0;
}
ElementCase<T> *p=head;
head=head->Next;
T retval=p->Data;
delete p;
size-=1;
return retval;
}

template <class T>
void File<T>::Reset(){
if(IsEmpty()){
cout<<"Vide"<<endl;
return;
}
int increment=size;
ElementCase<T> *p;
for(int i=1;i<=increment;i++){
p=head;
head=head->Next;
delete p;
size--;
}
}

template <class T>
void File<T>::operator>>(T &n){
ElementCase<T> *p;
if(!IsEmpty()){
n=Remove();
}
else cout<<"Vide"<<endl;
}

template <class T>
void operator<<(ostream &s, File<T> &f){
ElementCase<T> *p=f.head;
if(f.IsEmpty()){cout<<"File vide";return;}
for(int i=1;i<=f.size;i++){
s<<p->Data<<" ";
p=p->Next;
}
}

int main(){
File<int> file_int;
int IntInc=1;
for(int i=0;i<=10;i++) {
file_int<<IntInc;
IntInc++;
}

cout<<file_int;

File<double> file_double;

cout<<file_double.head->Data;
double DoubleInc=1.1;
for(int i=0;i<=10;i++) {
file_double<<DoubleInc;
DoubleInc++;
}
cout<<file_double;
}

[此贴子已经被作者于2006-3-24 5:24:03编辑过]

搜索更多相关主题的帖子: 操作符 实例 模板 重载 探讨 
2006-03-23 16:52
sunnvya
Rank: 5Rank: 5
等 级:贵宾
威 望:17
帖 子:1094
专家分:0
注 册:2005-11-23
收藏
得分:0 

不好意思
过下
没时间
呆会来!


http://www. 第二站>>>提供源码下载
2006-03-23 20:39
lizecn
Rank: 1
等 级:新手上路
帖 子:8
专家分:0
注 册:2006-3-23
收藏
得分:0 
File 类缺少构造函数
添加:
File() : size(0) {}

就搞定了
2006-03-23 20:56
快速回复:探讨类模板下的操作符重载的实例化
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015006 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved