c++ 数组模板类 出现bug

nkenen nkenen 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
#ifndef MyVextor_hpp__
#define MyVextor_hpp__

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

using namespace std;


template <typename T>
class MyVector
{
friend ostream &operator<<<T>(ostream &os, MyVector &myvt);
public:
MyVector();
MyVector(T *array,int len);
virtual ~MyVector();

friend ostream &operator<<<T>(ostream &os, MyVector &myvt);
T &operator[](int index);
MyVector &operator=(MyVector &other);

int len;
T *myvp;

};

template <typename T>
MyVector<T>::MyVector(){

cout << "无参构造函数..." << endl;
}

template <typename T>
MyVector<T>::MyVector(T *array, int len){

// if (*array != nullptr)
// {
// return;
// }

this->len = len;
this->myvp = new T[len + 1];
memset(this->myvp, 0, this->len + 1);
memcpy(this->myvp,array,len*sizeof(T));

}

template <typename T>
MyVector<T>::~MyVector(){

if (this->myvp != nullptr)
{
delete[] this->myvp;
this->myvp = nullptr;
}

}

template <typename T>
ostream &operator<<(ostream &os, MyVector<T> &myvt){

for (int i = 0; i < myvt.len;i++)
{
os << myvt.myvp[i] << " ";
}
os << endl;

return os;
}

template <typename T>
T &MyVector<T>::operator[](int index){

if (index > this->len)
{
cout << "operator[] 重载error" << endl;
}
return this->myvp[index];

}

template <typename T>
MyVector<T> &MyVector<T>::operator=(MyVector<T> &other){

if (this->myvp != nullptr)
{
delete[] this->myvp;
this->myvp = nullptr;
}

this->len = other.len;
this->myvp = new T[len + 1];
memset(this->myvp, 0, this->len + 1);
memcpy(this->myvp, other.myvp, len);

return *this;
}


#endif // MyVextor_h__

上面是数组模板类


#include "MyVextor.hpp"

class Teacher
{
public:
Teacher();
Teacher(char *name,int age);
~Teacher();

friend ostream &operator<<(ostream &os,Teacher &other);

private:
char *name;
int age;

};

Teacher::Teacher()
{
}

Teacher::Teacher(char *name, int age){

this->age = age;

this->name = new char[10];
strcpy(this->name, name);

}

Teacher::~Teacher()
{
if (this->name != nullptr)
{
delete[] this->name;
this->name = nullptr;
}
}

ostream &operator<<(ostream &os, Teacher &other){

os << "Teacher " << other.name << "age " << other.age << endl;

return os;

}


int main(){

char car[] = { 'a', 'b', 'c' };
int iar[] = {1,2,3};
Teacher Tar[] = { Teacher("skskd",45),Teacher("tyty",69),Teacher("sdsdsfg",68)};


//MyVector<char> cp(car,sizeof(car)/sizeof(char));
//MyVector<int> ip(iar, sizeof(iar) / sizeof(int));
MyVector<Teacher> Tp(Tar, sizeof(Tar) / sizeof(Teacher));

//cout << cp[1] <<endl;
//cout << cp;
//cout << ip;
cout << Tp;
return 0;
}

运行是成功的,但是在析构时出现问题,直接就崩了








...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
nkenen
C++ 语言 65,214 成员 250,514 内容