I have an assignment where I have to create a template class, create 2 objects one which takes 10 integers and sorts them, and the other which takes 10 strings and sorts them.
I have 2 questions which need to be addressed:
1) There is a big error when compiling, the syntax error states:
// error LNK1120: 2 unresolved externals
// error LNK2019: unresolved external symbol "public: __thiscall TWO<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,10>::~TWO<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,10>(void)" (??1?$TWO@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@$09@@QAE@XZ) referenced in function _main
// error LNK2019: unresolved external symbol "public: __thiscall TWO<int,10>::~TWO<int,10>(void)" (??1?$TWO@H$09@@QAE@XZ) referenced in function _main
2) Since I am using a template, how do I define the member prototype? In other words, instead of declaring the members in the class, I need to define them as function prototypes such as:
public: void ReadData();
void TWO :: ReadData() //this is incorrect apparently, why?
Here is my program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
template <class T, int n>
class TWO
{
private: T a[n];
public:
void ReadData() //reads data into array a
{
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
}
void DisplayData() //display the array
{
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
void SortArray() //sort the array
{
sort(a, a + 10);
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
~TWO(); //clean up object
};
int main()
{
TWO <int, 10> P;
TWO <string, 10> Q;
cout << "Enter 10 integers for object P: " << endl;
P.ReadData(); //reads 10 data from user
cout << "Enter 10 strings for object Q: " << endl;
Q.ReadData(); //reads 10 string data from user
cout << "The entry for object P is: " << endl;
P.DisplayData(); //display the data
cout << "The entry for object Q is: " << endl;
Q.DisplayData(); //display the data
cout << "The sorted array for object P: " << endl;
P.SortArray(); //display sorted int data
cout << "The sorted array for object Q: " << endl;
Q.SortArray(); //display sorted string data
system("PAUSE");
return 0;
}
|