如果需要保留代码中的T怎么办
时间: 2024-02-12 22:03:34 浏览: 36
如果你想在代码中保留 `T`,同时又想指定数组大小,你可以在模板类 `Array` 中增加一个非类型参数,表示数组的大小。例如:
```c++
template<typename T, int N>
class Array
{
public:
Array() {}
T sum()
{
T s = 0;
for (int i = 0; i < N; i++)
{
s += data[i];
}
return s;
}
void sort()
{
int i, j;
for (i = 0; i < N - 1; i++)
for (j = 0; j < N - 1 - i; j++)
if (data[j + 1] < data[j])
{
T temp = data[j + 1];
data[j + 1] = data[j];
data[j] = temp;
}
}
void print()
{
for (int i = 0; i < N; ++i)
{
cout << data[i] << " ";
}
cout << endl;
}
T& operator[](int index)
{
return data[index];
}
const T& operator[](int index) const
{
return data[index];
}
T data[N];
};
```
在 `main` 函数中,你可以使用 `Array<int, 10>` 来指定 `T` 为 `int`,同时数组大小为 `10`。例如:
```c++
int main()
{
Array<int, 10> arr = { 1, 5, 3, 4, 8, 6, 9, 0, 2, 7 };
cout << "Sum= " << arr.sum() << endl;
cout << "排序前: ";
arr.print();
arr.sort();
cout << "排序后: ";
arr.print();
return 0;
}
```
这样就可以同时保留 `T` 和指定数组大小了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)