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