MyArray.hpp文件
#pragma once
#include<string>
#include<iostream>
using namespace std;
template<class T>
class MyArray {
public:
MyArray(int capacity) {
this->mSize = 0;
this->mCapacity = capacity;
p = new T[this->mCapacity]; // 如果是自定义数据类型,会调用其无参构造。
// memset(this->p,0,sizeof(T)*(this->mCapacity)); // 初始化内存
// 问题1:为什么自定义数据类型有memset这一行输出就乱码,而内置数据类型int不会呢?
}
MyArray(const MyArray &m) { // 拷贝构造
this->mSize = m.mSize;
this->mCapacity = m.mCapacity;
this->p = new T[m.mCapacity];
// memset(this->p,0, this->mCapacity*sizeof(T));
// 问题2:但好像这里的memset对自定义数据类型没影响,有这一行却不会乱码?
memcpy(this->p, m.p, m.mSize * sizeof(T));
}
~MyArray() {
if (this->p != NULL) {
delete[] p;
p = NULL;
}
}
MyArray& operator=(const MyArray& m) {
if (this->p != NULL) {
delete[] p;
p = NULL;
}
this->p = new T[m.mCapacity];
this->mSize = m.mSize;
this.mCapacity = m.mCapacity;
// memset(this->p, 0, this->mCapacity * sizeof(T));
memcpy(this->p, m.p, m.mSize * sizeof(T));
return *this;
}
// 重载[]
T& operator[](int index) {
return this->p[index];
}
// 尾插
void push_back(const T& val) {
if (this->mSize == this->mCapacity) {
return;
}
this->p[this->mSize] = val;
this->mSize++;
}
// 尾删
void pop_back(const T& val) {
if (this->mSize == 0) {
return;
}
this->mSize--;
}
int getSize() {
return this->mSize;
}
void printMyarray() { // 打印基本数据类型
for (int i = 0; i < this->mSize; i++) {
cout << this->p[i] << " ";
}
cout << endl;
}
private:
T* p;
int mCapacity;
int mSize;
};
main函数.cpp文件
#include <iostream>
#include <string>
#include "MyArray.hpp"
using namespace std;
class Maker {
public:
Maker(string name, int age) {
this->name = name;
this->age = age;
}
Maker() { }
public:
string name;
int age;
};
void printMaker(MyArray<Maker> &m) {
for (int i = 0; i < m.getSize(); i++) {
cout << m[i].name << ":" << m[i].age << endl;
}
cout << endl;
}
int main(int argc, char** argv) {
MyArray<int> mArr(10); // 基本数据类型测试
mArr.push_back(1);
mArr.push_back(2);
mArr.push_back(3);
mArr.push_back(4);
mArr.printMyarray();
MyArray<int> mArr02(mArr); // 拷贝构造测试
mArr02.printMyarray();
MyArray<Maker> mkr(4);
Maker m1("孙悟空", 1);
Maker m2("ABC", 2);
Maker m3("123", 3);
Maker m4("123", 4);
mkr.push_back(m1);
mkr.push_back(m2);
mkr.push_back(m3);
mkr.push_back(m4);
printMaker(mkr);
MyArray<Maker> mkr02(mkr);
printMaker(mkr02);
MyArray<Maker> mkr03 = mkr02; // 测试 赋值符号 的重载
printMaker(mkr03);
system("pause");
return 0;
}