如何手动删除类的实例?

2024-04-22

如何手动删除类的实例?

Example:

#include <iostream>
#include <cstring>

class Cheese {
private:
    string brand;
    float cost;
public:
    Cheese(); // Default constructor
    Cheese(string brand, float cost); // Parametrized constructor
    Cheese(const Cheese & rhs); // Copy construtor
    ~Cheese(); // Destructor
    // etc... other useful stuff follows
}

int main() {
    Cheese cheddar("Cabot Clothbound", 8.99);
    Cheese swiss("Jarlsberg", 4.99);

    whack swiss; 
    // fairly certain that "whack" is not a keyword,
    // but I am trying to make a point. Trash this instance!

    Cheese swiss("Gruyère",5.99);
    // re-instantiate swiss

    cout << "\n\n";
    return 0;
}

在不知道用例或您想要解决的实际问题的情况下(请阅读XY 问题 http://xyproblem.info/,你的问题就是一个很好的例子)最简单的方法就是重新分配:

Cheese swiss("Jarlsberg", 4.99);
...
swiss = Cheese("Gruyère",5.99);

这当然可能需要您实现赋值运算符,但遵循三人或五人规则 http://en.cppreference.com/w/cpp/language/rule_of_three无论如何你都应该这样做(但是如果你遵循,则不需要赋值运算符零法则 http://en.cppreference.com/w/cpp/language/rule_of_three#Rule_of_zero).

You could如果您明确想要销毁当前的,也可以使用指针swiss object:

Cheese* swiss = new Cheese("Jarlsberg", 4.99);
...
delete swiss;
swiss = new Cheese("Gruyère",5.99);

但指针是一大堆你应该避免的蠕虫,并且在现代 C++ 中并不真正需要太多。但是如果您想要多态性,则需要指针(或引用)。然后,您可以有一个指向实际实例的基类指针,并且诸如虚函数之类的东西将按预期工作。

另外,根据我们仍然一无所知的您的情况,您当然可以使用范围界定:

Cheese swiss("Jarlsberg", 4.99);
...
{
    Cheese swiss("Gruyère",5.99);
    // In here the swiss cheese is a Gruyère
    ...
}
// Out here the swiss cheese is a Jarlsberg

尽管像这样隐藏变量名是可行的,但这是一个应该避免的坏习惯,因为它会给代码读者带来困惑。另一方面,即使使用作用域,也没有什么可以阻止您使用所需的任何(有效)变量名称,因此您可以命名外部作用域实例jarlsberg和内部范围实例gruyere, the gruyere然后,对象将在作用域末尾被破坏,就像任何其他嵌套作用域变量将被破坏并“消失”一样。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何手动删除类的实例? 的相关文章

随机推荐