【发布时间】:2013-04-11 12:47:53
【问题描述】:
如何在increment 函数中访问变量itemtype 和total?我下面的代码给了我如下错误
Counter2.h:在成员函数'int Counter::increment(T)'中:
Counter2.h:28:31: 错误:“itemtype”未在此范围内声明
Counter2.h:36:22: 错误:“itemtype”未在此范围内声明
Counter2.h:36:39: 错误:'total' 未在此范围内声明
我必须能够使用命令Counter<T> counter;,其中T可以是任何类型,例如字符串和counter.increment()
#include<string>
//#include<cstdlib>
#include<vector>
using std::vector;
using std::string;
template<class T>
class Record{
public:
T itemtype;
int total;
};
template<class T>
class Counter{
vector< Record<T> > data;
public:
int increment(T item);
int count(T item);
void printSummary();
};
template<class T>
int Counter <T> :: increment(T item){
bool check = false;
for(int i=0; i < data.size(itemtype); i++){
if(data[i].itemtype == item){
data[i].total++;
bool check = true;
break;
}
}
if(check == false){
data.push_back(itemtype = item, total = 1);
}
}
int main(){
Counter<string> counter;
counter.increment("orange");
counter.increment("orange");
return 0;
}
【问题讨论】:
标签: c++ function templates vector stl