gpt4 book ai didi

c++ - 模板类的析构函数

转载 作者:行者123 更新时间:2023-11-27 23:49:15 24 4
gpt4 key购买 nike

我有模板类。其中一个参数是 char*std::string。所以我必须删除 char*,并且不要删除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 != &param)
{
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 != &param)
{
// 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 的评论是实际的解决方案。)

关于c++ - 模板类的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47821945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com