注册 登录
编程论坛 C++教室

主函数模版调用问题

zcdjt 发布于 2014-10-12 20:48, 361 次点击
如例子void List<T>::Create(T a[], int n)
singleList.Create(a,10)
这个a的类型应该怎样定义才能通过运行?
(1)singleList.Create(int a,10)
(2)singleList.Create<int>(a,10)
以上两种情况有错。
3 回复
#2
rjsp2014-10-13 08:24
比如
double f[10];
singleList.Create(f,10);
#3
stop12042014-10-13 09:29
其实是这样
T a;       //正常都是在函数下直接输入a就可以了.
            //如果要新的变量b跟a的类型一样就直接 T b;
singleList.Create(a,10) ;

-----------
程序代码:


#include "iostream"
using namespace std;
//template<class T> T Return(T a, int n = 0); //加入本句转成非内联函数
template<class T> T Return(T a, int n = 0)
{
    cout.setf( ios::left); //输出格式
    cout.width(6);        //输出格式
                        
//T b = a;   //b的类型跟a的一样.
    cout << a << " ----- " << sizeof a << endl;
}
int main()
{

    Return('a');     //字符
    Return("1aa");     //字符串
    Return(1.1);     //小数
    Return(1);       //整数
    Return(1e+5);    //
    Return(1e+20);   //
    return 0;
}
/*
a      ----- 1
1aa    ----- 4
1.1    ----- 8
1      ----- 4
100000 ----- 8
1e+020 ----- 8
*/


[ 本帖最后由 stop1204 于 2014-10-13 09:45 编辑 ]
#4
zcdjt2014-10-14 22:52
谢了!
1