| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 346 人关注过本帖
标题:C++默认参数的类模板的问题
只看楼主 加入收藏
zhuzhidu784
Rank: 1
等 级:新手上路
帖 子:12
专家分:4
注 册:2011-5-3
结帖率:100%
收藏
已结贴  问题点数:10 回复次数:1 
C++默认参数的类模板的问题
程序代码:
#include<iostream>
using namespace std;
template<typename AType=int,int size = 10>
class atype
{

 public:
  atype()
  {
   int i;
   for(i=0;i<size;i++) array[i]=i;
  }
  AType& operator[](int n);

 private:
  AType array[size];
};
template<typename AType,int size>AType& atype<AType,size>::operator [](int n)
{

 if(n<0||n>=size)

 {cout<<"下标"<<n<<"超出范围!!!"<<endl;

 exit(1);

 }

 return array[n]=n;
}
int main()
{

 atype<int,12>intob;

 atype<double>doubleob;

 atype<>defaultob;

 int i;

 cout<<"int数组:";

 for(i=0;i<12;i++) intob[i]=i;

 for(i=0;i<12;i++)
  cout<<intob[i]<<"  ";

 cout<<endl;

 cout<<"double数组:";

 for(i=0;i<10;i++) doubleob[i]=(double)i/2;

 for(i=0;i<10;i++)
  cout<<doubleob[i]<<"  ";

 cout<<endl;

 cout<<"默认数组:";

 for(i=0;i<10;i++)

 for(i=0;i<10;i++)
  cout<<defaultob[i]<<"  ";

 cout<<endl;

 return 0;
}

为什么不能实现double数组的正确显示

0    0.5   1   1.5   2   2.5   3   3.5   4   4.5

2011-05-05 13:34
specilize
Rank: 4
等 级:业余侠客
帖 子:126
专家分:247
注 册:2011-2-20
收藏
得分:10 
template<typename AType,int size>AType& atype<AType,size>::operator [](int n)
这里出问题啦,形参是int n,就算你传给n的是double,也会被转换为int,所以就不输出小数咯
2011-05-05 19:03
快速回复:C++默认参数的类模板的问题
数据加载中...
 
   



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

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