黑马程序员视频链接
MyArray.hpp
// Created by chenh on 2023/1/14.
#ifndef TEMPLATE_MYARRAY_H
#define TEMPLATE_MYARRAY_H
#include <iostream>
#include <string>
using namespace std;
template<class T>
class MyArray {
public:
MyArray(int capacity) {
cout << "parameter constructor" << endl;
this->_size = 0;
this->_capacity = capacity;
this->_array = new T [this->_capacity];
}
MyArray(const MyArray &obj) {
cout << "copy constructor" << endl;
this->_array = new T [obj._capacity];
this->_size = obj._size;
this->_capacity = obj._capacity;
for (int i = 0; i < this->_size; ++i) {
this->_array[i] = obj._array[i];
}
}
~MyArray() {
cout << "destruction" << endl;
delete[] this->_array;
}
MyArray &operator=(const MyArray &obj) {
cout << "operator overloading" << endl;
if (this->_array != NULL) {
delete[] this->_array;
}
this->_array = new T[obj._capacity];
this->_size = obj._size;
this->_capacity = obj._capacity;
for (int i = 0; i < this->_size; ++i) {
this->_array[i] = obj._array[i];
}
return *this;
}
T &operator[](int index) {
if (index <= this->_size) return this->_array[index];
}
void push(T data) {
if (this->_size < this->_capacity)
this->_array[this->_size++] = data;
}
void pop(T data) {
if (this->_size > 0) {
this->_size--;
}
}
int get_size() {
return this->_size;
}
int get_capacity() {
return this->_capacity;
}
private:
T *_array;
int _size;
int _capacity;
};
#endif // TEMPLATE_MYARRAY_H
main.cpp
#include <iostream>
#include <string>
#include "MyArray.hpp"
using namespace std;
template<class T1, class T2>
class Person {
public:
Person() {};
Person(T1 name, T2 age) {
this->name = name;
this->age = age;
}
T1 name;
T2 age;
};
void printArray(MyArray<int> &p) {
for (int i = 0; i < p.get_size(); ++i) {
cout << p[i] << " ";
}
cout << endl;
}
void test01() {
MyArray<int> p1(5);
for (int i = 0; i < p1.get_capacity(); ++i) {
p1.push(i);
}
printArray(p1);
}
void printArray(MyArray<Person<string, int>> &arr) {
for (int i = 0; i < arr.get_size(); ++i) {
cout << "name: " << arr[i].name << " age:" << arr[i].age << endl;
}
}
void test02() {
Person<string, int> p1("Tang monk", 40);
Person<string, int> p2("Monkey king", 9999);
Person<string, int> p3("Pigsy", 5000);
Person<string, int> p4("Sandy", 3000);
MyArray<Person<string, int>> arr(5);
arr.push(p1);
arr.push(p2);
arr.push(p3);
arr.push(p4);
arr.pop(p4);
printArray(arr);
}
int main() {
test02();
return 0;
}
- 值传递,会导致拷贝构造,所以要使用引用传入或返回
- 无参构造牢记,养成习惯
- 模板,我将其理解为,一个存放变量类型的变量