尝试定义二维关联数组时,我在类中编写了模板运算符,使其更接近原始数组。这是我的操作员功能。使用模板运算符创建二维关联数组
template <class T, class U, class V>
T& TwoAssocDArray<T,U,V>::operator [](U input1)[](V input2) {
for(int i=0; i<size(); i++)
if(stack[i].key1 == input1 && stack[i].key2 == input2)
return stack[i].d;
DataPack pack;
pack.key1 = input1;
pack.key2 = input2;
stack.push_back(pack);
return stack[size].d;
}
类接口,
#ifndef _DATASTRUCTURE_H_
#define _DATASTRUCTURE_H_
#include <vector>
using namespace std;
template <class T, class U, class V>
class TwoDAssocArray {
private:
typedef struct _DataPack {
T d;
U key1;
V key2;
} DataPack;
vector<DataPack> stack;
public:
int size();
bool isIn(U input1, V input2);
bool add(T data, U input1, V input2);
T get(U input1, V input2);
T& operator [](U input1)[](V input2);
};
#endif
然后我测试了它在main()。
int main(int argc, char *argv[]) {
TwoDAssocArray<int, char*, char*> assocArr;
assocArr["in1"]["in2"] = 2246001;
cout << assocArr["in1"]["in2"] << endl;
return 0;
}
生成并运行后,我发现它没有工作,得到了十几个错误。 我认为主要原因是我不熟悉的模板语法。 我相信大量的错误总是来自几个语法错误。
如果有人愿意帮助我,我将不胜感激。
你应该检查你的设计:类似'arr [x] [y]''需要一个'arr'对象,它支持'[]'访问并返回另一个适合第二个[]]访问的对象。 – 2014-09-19 03:42:10