如何在析构函数中调用成员函数。

3

我正在进行一个C++项目,但是我想知道如何在析构函数中调用类/结构体的成员函数。我的项目其余部分进展顺利,所以我只需要知道这一点就可以完成它 :)

    ~Drink()
    {
        cout << "hi";
        cout << "I want to know how to summon a member function from a destructor.";
    }

    int Drink::dailyReport()
    {
        cout << "This is the member function I want to call from the destructor.";
        cout << "How would I call this function from the destructor?"
    }

请正确编写语法!提供如何在析构函数中调用成员函数的示例将很好!

2个回答

3

问题在于你没有在析构函数前加上 Drink:: 前缀。

由于析构函数不知道它应该关联哪个类(假设它是在类声明之外定义的),它甚至不知道它有一个成员函数可以调用。

尝试重写你的代码为:

Drink::~Drink() // this is where your problem is
{
    cout << "hi";
    cout << "I want to know how to summon a member function from a destructor.";
    dailyReport(); // call the function like this
}

int Drink::dailyReport()
{
    cout << "This is the member function I want to call from the destructor.";
    cout << "How would I call this function from the destructor?"
}

啊,是的,谢谢你指出来,我刚刚编辑了更改 :) - Geoffrey Tucker
啊,谢谢!我以为这会更加复杂,但很高兴它其实很简单! - Alan Sahbegovic

1

类析构函数基本上和其他成员函数一样:你可以像平常一样调用类的成员函数和使用成员变量,但是:

  1. 当然要记住,析构函数旨在清理和(如果您手动处理)释放资源和动态内存等,因此您可能不应该在析构函数中做太多事情。

  2. 如果你的类变得足够复杂以使用虚函数,事情就变得有些棘手了。

  3. 建议:在析构函数中小心不要执行任何可能会抛出异常但未处理的操作。这可能会引入令人讨厌且难以发现的错误。


2
这就是为什么你总是要声明你的析构函数为 noexcept。总是。 - Vincent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接