定义类模板实现对数组类中数组元素的查找和求和功能.

设计一个类模板
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 <类型参数表>

返回值类型  类模板名<类型参数名列表>::成员函数名(参数表)

{

 ...

}

参考资料来源:

百度百科——类模板

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-06-04

#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;

}

本回答被提问者采纳
第2个回答  2013-06-04
#include<iostream>
using namespace std;
const int row=2,col=3;

template<class  T>
class array

public: 
array()
{  
    for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
    cin>> var[i][j];
}

void find(T x)
{
    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;
}
}

T sum()
{
    T sum = 0;
    for(int i = 0; i < row; ++i)
for(int j = 0; j < col; ++j)
    sum += var[i][j];
    return sum;
}

private:
T var[row][col];
};

int main()
{
cout << "int 测试(输入6个整数)" << endl;
array<int> arr_i;

cout << "请输入要找的整数: " << flush;
int i;
cin >> i;
arr_i.find(i);

cout << "int型array的和为:"<< arr_i.sum() << endl << endl;


cout << "double 测试(输入6个小数)" << endl;
array<double> arr_d;

cout << "请输入要找的小数: " << flush;
double d;
cin >> d;
arr_d.find(d);

cout << "double型array的和为:" << arr_d.sum() << endl;

return 0;
}

相似回答