我正在使用朋友类,当我从列表类调用DeleteItem时,我想使用rec的析构函数。但是,有一个指向我要删除的记录的指针,所以我不知道如何调用析构函数,所以它会做我想要的。 类:
class rec
{
friend class list;
private:
char * id;
char firstname[15];
char lastname[15];
int ar[10];
rec* prev;
rec* next;
public:
void SetData ( char * id_in, char * fn, char * ln, int * ans_in);
rec( char *i, char *fn, char *ln, int *a);
rec();
void operator= (const rec& r);
rec (const rec& r);
void Print();
~rec();
};
class list
{
private:
rec* first;
rec* last;
public:
int AddItem(rec r);
int DeleteItem (char* delid);
void PrintList( int order);
int ReadData(char *inanswer, char *inkey);
int WriteData(char *answer, char *key);
list();
void operator= (list l);
private:
int CheckDuplicate(rec r);
void DeleteData();
int Count(char *filename);
};
〜REC()
rec :: ~rec()
{
if (id != NULL)
{
delete [] id;
}
}
DeleteItem(Snipet)
int list :: DeleteItem(char *delid)
{
int id_counter;
rec *current = first;
while (current || current == NULL)
{
if (current == NULL)
{
return 0;
}
else
{
id_counter = strcmp(current -> id, delid);
if (id_counter != 0)
{
current = current -> next;
}
else
{
if (current == first && current != last)
{
~rec(); //Here
first = current -> next;
delete current;
first -> prev = NULL;
return 1;
}
如果我手动输入delete[] current ->id;
,删除项将编译正常但是当我尝试按原样编译时这样做
list.cpp:292: error: no match for ‘operator~’ in ‘~rec()’
/usr/lib/gcc/x86_64-redhat-linux/4.3.0/../../../../include/c++/4.3.0/bits/ios_base.h:105: note: candidates are: std::_Ios_Fmtflags std::operator~(std::_Ios_Fmtflags)
/usr/lib/gcc/x86_64-redhat-linux/4.3.0/../../../../include/c++/4.3.0/bits/ios_base.h:145: note: std::_Ios_Openmode std::operator~(std::_Ios_Openmode)
/usr/lib/gcc/x86_64-redhat-linux/4.3.0/../../../../include/c++/4.3.0/bits/ios_base.h:183: note: std::_Ios_Iostate std::operator~(std::_Ios_Iostate)
是我的析构函数需要修复还是在DeleteItem中执行某些操作?
答案 0 :(得分:2)
要调用析构函数,语法为current->~rec()
,但在大多数情况下,您不应该直接在C ++中调用析构函数。通过调用delete current
,C ++将在取消分配内存之前自动调用析构函数。
在你的情况下,因为你在调用delete
之后也使用~rec()
,你的析构函数将被调用两次,因此当你的构造函数试图释放{{}时,你将导致双重自由损坏1}}记忆。
建议:为了避免使用好友类,在您的情况下,id
和next
成员与prev
相关,而不是{{1 } .class。因此,您的list
类可以有一个嵌套的装饰器类,它将包裹您的rec
类,如:
list
然后,列表的逻辑将与rec
类的逻辑完全隔离。