classtemplaterecursion.cpp
来自「C++ sample code, for the book: C++ blac」· C++ 代码 · 共 67 行
CPP
67 行
#include <iostream>
using namespace std;
template <class T, int number_of_elements>
class Array
{
T *ptr_to_array;
public:
explicit Array();
Array(const Array & a);
~Array();
T& operator= (const Array & a);
T& operator[](int index) {return ptr_to_array[index];}
};
template <class T, int number_of_elements>
Array<T, number_of_elements>::Array()
{
ptr_to_array = new T[number_of_elements];
}
template <class T, int number_of_elements>
Array<T, number_of_elements>::Array(const Array & a)
{
number_of_elements = a.number_of_elements;
T *ptr_to_array = new T[number_of_elements];
for(int loop_index = 0; loop_index < number_of_elements; loop_index++) {
ptr_to_array[loop_index] = a.ptr_to_array[loop_index];
}
}
template <class T, int number_of_elements>
T& Array<T, number_of_elements>::operator= (const Array & a)
{
if(this == &a) return *this;
delete[] ptr_to_array;
number_of_elements = a.number_of_elements;
T *ptr_to_array = new T[number_of_elements];
for(int loop_index = 0; loop_index < number_of_elements; loop_index++) {
ptr_to_array[loop_index] = a.ptr_to_array[loop_index];
}
return *this;
}
template <class T, int number_of_elements>
Array<T, number_of_elements>::~Array()
{
delete[] ptr_to_array;
}
int main()
{
Array<Array<float, 3>, 10> scores;
scores[0][1] = 85;
cout << "The student scored " << scores[0][1] << endl;
return 0;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?