如何使用指针 C++ 将 class 的析构函数转换为另一个 class 的析构函数?类似于节点的单向列表容器 class 和 class
How to make a destructor for class into another class with pointers C++? Something like one-direction list container class and class of nodes
class lista {
class wezel {
wezel *nast; // next node in list
std::string napis; // string in node
// ...
public:
void set_napis(string napis1) { napis = napis1; }
void set_nast(wezel *nast1) { nast = nast1; }
wezel(const std::string napis1, wezel *nast1) : napis(napis1), nast(nast1) {}
friend ostream& operator<< (ostream &wy, const wezel &wzl) {
if (wzl.nast) return wy << wzl.napis << ", " << *wzl.nast;
else return wy << wzl.napis;
}
};
wezel *poczatek; // pointer to the beg of the list
public:
lista();
lista(const lista &lst);
lista(lista &&lst);
lista(initializer_list<std::string> lst);
lista& operator= (const lista &lst);
lista& operator= (lista &&lst);
~lista();
public:
friend ostream& operator<< (ostream &wy, const lista &lst) {
if (lst.poczatek) return wy << "(" << *lst.poczatek << ")";
else return wy << "()";
}
};
我想编写不仅删除 class lista 的成员而且删除 wezel(所有节点)的析构函数 wezel 中的指针意味着指向列表的下一个元素的指针是 *nast。如果它是空指针,它就是列表的末尾。我知道我不应该为字符串创建任何析构函数,但是那些指针等呢?
非常抱歉我的英语不好。我来自波兰 ;) 问候 ;)
这里的问题是您无法控制 wezel
的创建方式。如果它们是用 new
创建的,很好,只是 delete
它们。但是如果一堆是用 new[]
创建的,那么它们应该用 delete[]
销毁,如果一个是刚刚在 在堆栈 中创建的(wezel wezel1("mystring");
) 它根本不应该被删除:它会在声明它的函数或块的末尾自动消失。
TL/DR:除非 API 明确声明 lista
中的所有 wezel
必须 已使用 new
, 你不应该尝试删除它们。
或者:您应该使用 lista
中的方法来添加新字符串并使用 new
在该方法中创建 wezel
。这样你就可以控制它的创建方式并可以安全地 delete
它。
class lista {
class wezel {
wezel *nast; // next node in list
std::string napis; // string in node
// ...
public:
void set_napis(string napis1) { napis = napis1; }
void set_nast(wezel *nast1) { nast = nast1; }
wezel(const std::string napis1, wezel *nast1) : napis(napis1), nast(nast1) {}
friend ostream& operator<< (ostream &wy, const wezel &wzl) {
if (wzl.nast) return wy << wzl.napis << ", " << *wzl.nast;
else return wy << wzl.napis;
}
};
wezel *poczatek; // pointer to the beg of the list
public:
lista();
lista(const lista &lst);
lista(lista &&lst);
lista(initializer_list<std::string> lst);
lista& operator= (const lista &lst);
lista& operator= (lista &&lst);
~lista();
public:
friend ostream& operator<< (ostream &wy, const lista &lst) {
if (lst.poczatek) return wy << "(" << *lst.poczatek << ")";
else return wy << "()";
}
};
我想编写不仅删除 class lista 的成员而且删除 wezel(所有节点)的析构函数 wezel 中的指针意味着指向列表的下一个元素的指针是 *nast。如果它是空指针,它就是列表的末尾。我知道我不应该为字符串创建任何析构函数,但是那些指针等呢?
非常抱歉我的英语不好。我来自波兰 ;) 问候 ;)
这里的问题是您无法控制 wezel
的创建方式。如果它们是用 new
创建的,很好,只是 delete
它们。但是如果一堆是用 new[]
创建的,那么它们应该用 delete[]
销毁,如果一个是刚刚在 在堆栈 中创建的(wezel wezel1("mystring");
) 它根本不应该被删除:它会在声明它的函数或块的末尾自动消失。
TL/DR:除非 API 明确声明 lista
中的所有 wezel
必须 已使用 new
, 你不应该尝试删除它们。
或者:您应该使用 lista
中的方法来添加新字符串并使用 new
在该方法中创建 wezel
。这样你就可以控制它的创建方式并可以安全地 delete
它。