如何访问变量itemtype
和函数total
内increment
?我下面的代码给了我如下错误
Counter2.h:在成员函数'int Counter::increment(T)'中:
Counter2.h:28:31: 错误: 'itemtype' 未在此范围内声明
Counter2.h:36:22: 错误: 'itemtype' 未在此范围内声明
Counter2.h:36:39:错误:未在此范围内声明“总计”
我必须能够使用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;
}