為什么用了類模板之后編譯一直報錯,是類模板使用錯了嗎




這是代碼:
Sort.h檔案:
#include <iostream>
using namespace std;
#define M 5
template <class T> //類模板
class Sort
{
private:
T a[M];
public:
void Input(); //輸入M個數
void Print(); //輸出M個數
void sort(); //冒泡排序(從小到大)
void sort2(); //冒泡排序(從大到小)
};
Sort.cpp檔案:
#include "Sort.h"
template <class T> //類模板
void Sort<T>::Input() //輸入M個數
{
int i;
cout << "請輸入" << M << "個數:" << endl;
for (i = 0; i < M; i++)
{
cin >> a[i];
}
}
template <class T> //類模板
void Sort<T>::Print() //輸出M個數
{
int i;
cout << "輸入的資料為:";
for (i = 0; i < M; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
template <class T> //類模板
void Sort<T>::sort() //冒泡排序(從小到大)
{
int i, j, temp;
for (i = 0; i < M - 1; i++)
{
for (j = 0; j < M - 1 - i; j++)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
main.cpp檔案
#include "Sort.h"
template <class T> //類模板
int main()
{
Sort s;
s.Input(); //像物件中重新輸入陣列值
s.Print(); //輸出新輸入的陣列值
s.sort(); //將新輸入的值從小到大進行排列
s.Print(); //輸出排序后的值
system("pause");
return 0;
}
uj5u.com熱心網友回復:
供參考:#include <iostream>
using namespace std;
#define M 5
template <class T> //類模板
class Sort
{
private:
T a[M];
public:
void Input(); //輸入M個數
void Print(); //輸出M個數
void sort(); //冒泡排序(從小到大)
void sort2(); //冒泡排序(從大到小)
};
//Sort.cpp檔案:
//#include "Sort.h"
template <class T> //類模板
void Sort<T>::Input() //輸入M個數
{
int i;
cout << "請輸入" << M << "個數:" << endl;
for (i = 0; i < M; i++)
{
cin >> a[i];
}
}
template <class T> //類模板
void Sort<T>::Print() //輸出M個數
{
int i;
cout << "輸入的資料為:";
for (i = 0; i < M; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
template <class T> //類模板
void Sort<T>::sort() //冒泡排序(從小到大)
{
int i, j, temp;
for (i = 0; i < M - 1; i++)
{
for (j = 0; j < M - 1 - i; j++)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
//main.cpp檔案
//#include "Sort.h"
//template <class T> //類模板
int main()
{
Sort<int> s;//Sort s;
s.Input(); //像物件中重新輸入陣列值
s.Print(); //輸出新輸入的陣列值
s.sort(); //將新輸入的值從小到大進行排列
s.Print(); //輸出排序后的值
system("pause");
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/251843.html
標籤:C++ 語言
