模板类的驱动器
Destructor for template class
本文关键字:驱动器 更新时间:2023-10-16
我有模板类。其中一个参数是char*
或std::string
。因此,我必须删除char*
,然后Don t delete
STD :: String``。我不知道该怎么办。
template <typename T>
class Discipline
{
public:
unsigned int getLectureHours() const { return lecture_hours; }
unsigned int getTotalHours() const { return total_hours; }
unsigned int getPracticalHours() const { return practical_hours; }
unsigned int getSelfHours() const { return self_hours; }
T getName() const { return name; }
Date& getDate() const { return date; }
Discipline() : date(1,1,2000), name("Math"), total_hours(10), lecture_hours(4), practical_hours(4), self_hours(2) {}
Discipline(Date* tdate, T& tname, int& t1, int& t2, int& t3) : date(*tdate), name(tname), total_hours(t1), lecture_hours(t2), practical_hours(t3), self_hours(t1-t2-t3){}
Discipline(const Discipline<T>& other)
{
*this = other;
name = "def";
}
Discipline<char*>& operator=(const Discipline<char*>& param)
{
if (this != ¶m)
{
this->name = new char[strlen(param.name)+1];
strcpy(this->name, param.name);
this->date = param.date;
this->total_hours = param.total_hours;
this->lecture_hours = param.lecture_hours;
this->self_hours = param.self_hours;
this->practical_hours = param.practical_hours;
}
return *this;
}
Discipline<std::string>& operator=(const Discipline<std::string>& param)
{
if (this != ¶m)
{
// this->name = "";
// this->name += "def";
this->date = param.date;
this->total_hours = param.total_hours;
this->lecture_hours = param.lecture_hours;
this->self_hours = param.self_hours;
this->practical_hours = param.practical_hours;
}
return *this;
}
~Discipline<char*>() { delete[] name; }
private:
Date date;
T name;
unsigned int total_hours;
unsigned int lecture_hours;
unsigned int practical_hours;
unsigned int self_hours;
};
有明确的专业化。在实施中,您可以像
一样template<>
Discipline<string>::~Discipline(){}
template<>
Discipline<char*>::~Discipline(){
delete[] name;
}
这甚至可以灵活地完成:
template<class T>
Discipline<T>::~Discipline(){}
template<>
Discipline<char*>::~Discipline(){
delete[] name;
}
此变体将通过char*
在类上删除delete,如果您打算将来添加更多专业化,则在其他情况下在灾难中无能为力。
您可能需要阅读http://en.cppreference.com/w/cpp/language/template_specialization
(只是为了回答问题。当然,Antred的评论是实际解决方案。)
一个变体是添加一个简单的静态方法,例如deetthestring,并带有两个参数过载。然后,您只需使用模板类型值调用,然后让编译器决定。
另一个变体是将char*包裹在unique_ptr []中,因此它会删除自身。您可以通过让小适配器类Safestore具有成员typedef std::string as
,而Safestore具有typedef std::unique_ptr<char[]> as
。
相关文章:
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- 在QTreeView中仅显示共享驱动器和文件夹
- QT MYSQL 驱动器构建,未定义对"mysql_get_client_version@0"的引用
- 通过搜索硬盘驱动器查找文件目录
- 如何确定SSD驱动器是固定驱动器还是连接在USB上
- 关于从驱动器中删除文件的问题
- 如何使用libusb获取驱动器名称?
- 如何确定文件或文件夹是在SSD还是硬盘驱动器上?
- Qt驱动器下拉列表仅列出USB记忆棒
- C++ gtkmm:文件选择器对话框不适用于任何驱动器
- 使用 MFC c++ 删除已装载驱动器的文件
- 阻止访问映射的网络驱动器
- 驱动器号上的查找文件失败,但在路径上传递
- 将硬盘驱动器上的 BIT XXX 从 0 更改为 1
- 更改 ICDBurn 窗口 API 中的默认刻录驱动器
- C 操作员超载调用驱动器
- 在字符串驱动器中读取访问违规
- 为什么std ::异常驱动器不否
- 为什么在将值分配给对象时,为什么要调用构造函数和驱动器
- 删除其他类的类驱动器