- 论坛徽章:
- 0
|
惭愧,泛型用的太少,请各位达人指点。
问题
==============================
当不适用迭代器做遍历时,工作正常。
[root@csg-dev1 _code]# g++ -o generic_test generic_test.cpp
[root@csg-dev1 _code]# ./generic_test
1
3
编译使用迭代器的那段,不通过
[root@csg-dev1 _code]# g++ -D__IT__ -o generic_test generic_test.cpp
generic_test.cpp: In member function `int GTest<RecType>: ump()':
generic_test.cpp:21: error: expected `;' before "p"
generic_test.cpp:22: error: `p' was not declared in this scope
generic_test.cpp: In member function `int GTest<RecType>: ump() [with RecType = int]':
generic_test.cpp:44: instantiated from here
generic_test.cpp:21: error: dependent-name ` std::vector<RecType,std::allocator<_CharT> >::iterator' is parsed as a non-type, but instantiation yields a type
generic_test.cpp:21: note: say `typename std::vector<RecType,std::allocator<_CharT> >::iterator' if a type is meant
Code
============================
1 /* generic_test.cpp */
2 #include <iostream>
3 #include <vector>
4
5 using namespace std;
6
7 template <class RecType>
8 class GTest
9 {
10 public:
11 GTest(){};
12 virtual ~GTest(){};
13
14 void AddRec(RecType &r)
15 {
16 mV.push_back(r);
17 }
18
19 int Dump()
20 {
21 #ifdef __IT__
22 vector<RecType>::iterator p;
23 for (p=mV.begin(); p!=mV.end(); p++) {
24 cout<<*p<<endl;
25 }
26 #else
27 int s=mV.size();
28 for (int i=0; i<s; i++)
29 {
30 cout<<mV[i]<<endl;
31 }
32 #endif
33 }
34 private:
35 vector<RecType> mV;
36 };
37
38 int main()
39 {
40 GTest<int> gt;
41 int a=1;
42 gt.AddRec(a);
43 a=3;
44 gt.AddRec(a);
45 gt.Dump();
46 return 0;
47 } |
==========================================
[ 本帖最后由 PinkOrient 于 2009-7-10 09:06 编辑 ] |
|