设计一个类模板
const int cow=2,col=3;
template<calss T>
class array
{ T var[row][col];
public:
array( )
{ for(int i=0;i<cow;i++)
for(int j=0;j<cow;j++)
cin>> var[i][j];
}
void find(T a);
T sum( );
};
请将类模板的定义补充完整,然后在main中产生类型实参分别为int和double型的两个模板类,分别对整型数组和双精度数组完成所要求的功能。
我写的是
#include<iostream>
using namespace std;
const int row=2,col=3;
template<class T>
class array
{ T var[row][col];
public:
array()
{ for(int i=0;i<cow;i++)
for(int j=0;j<cow;j++)
cin>> var[i][j];
}
template<class T>
void find(T x){
int i=0,j=0
for(int i=0;i<cow;i++)
for(int j=0;j<cow;j++)
{ if (var[i][j]=x)
cout<<"the name is a["<<i<<"]["<<j<<"]"<<endl;
}
template<class T>
T sum()
T a[],sum=0;
for(int i=0;i<cow;i++)
for(int j=0;j<cow;j++)
sum+=a[i][j];
return sum;
};
};
int main()
{
array b;
b.find(3);
b.sum(a);
cout<<b.find<<" "<<b.sum<<endl;
return 0;
}
有一个错误,求解,新手求指教
代码如下:
class Box
{
private:
int a, b, c;
public:
int V;
Box(int ch,int k,int g)
{
a = ch;
b = k;
c = g;
V = a*b*c;
}
扩展资料
C++ 中类模板的写法如下:
template <类型参数表>
class 类模板名{
成员函数和成员变量
};
类型参数表的写法如下:
class类塑参数1, class类型参数2, ...
类模板中的成员函数放到类模板定义外面写时的语法如下:
template <类型参数表>
返回值类型 类模板名<类型参数名列表>::成员函数名(参数表)
{
...
}
参考资料来源:
#include<iostream>
using namespace std;
const int row=2,col=3;
template<class T>
class array
{
T var[row][col];
public:
array()
{ for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
cin>> var[i][j];
}
//template<class T>
void find(T x){
//int i=0,j=0;
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
{ if (var[i][j]==x)
cout<<"the name is a["<<i<<"]["<<j<<"]"<<endl;
}
}
//template<class T>
T sum()
{T sum1=0;
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
sum1+=var[i][j];
return sum1;
}
};
int main()
{
array<int> b;
b.find(3);
//b.sum();
cout<<" "<<b.sum()<<endl;
array<double> c;
c.find(3);
//b.sum();
cout<<" "<<c.sum()<<endl;
return 0;
}
本回答被提问者采纳