⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 classtemplatemulticlass.cpp

📁 C++ sample code, for the book: C++ black book, including templates, exceptional handling.
💻 CPP
字号:
#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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -