【问题标题】:After using destructors, the code shows "reference to Book::~Book()" error使用析构函数后,代码显示“reference to Book::~Book()”错误
【发布时间】:2016-02-23 16:38:11
【问题描述】:

我是 C++ 的学习者,我正在研究构造函数和析构函数。我已经编译了下面的代码,它返回对 Book::~Book() 错误的未定义引用。但是当我注释掉析构函数时,它工作正常。我想我可以在使用析构函数后创建成员函数。我在这里做错了什么?我在下面编写了我的代码以便更好地理解

class Book
{
private:
    int *pages;
    int *price;

public:
    Book()        //default constructor
    {
        pages = new int;
        price = new int;
        *pages = 300;
        *price = 8;
    };  

    void pre_destructor()
    {
        std::cout << "The pages:" << *pages;
        std::cout << "The price:" << *price;
    }

~Book();             //destructor

    void post_destructor()
    {
        std::cout << "The pages:" << *pages << "\n";
        std::cout << "The price:" << *price << "\n";
        delete pages;
        delete price;
    }
};

int main()
{
    using namespace std;
    Book book1;

    cout << "Before using destructors" << endl;
    cout << "---------------------------------"<< endl;

    book1.pre_destructor();

    cout << "After using destructors" << endl;
    cout << "---------------------------------";

    book1.post_destructor();

    return 0;
}  //destructor is called here

【问题讨论】:

  • 欢迎来到 SO!你忘了实现析构函数; ~Book();只是它的声明。
  • 我进行了编辑。但现在它显示“预期;在成员声明的末尾”指向调用析构函数的行
  • 如果您必须手动调用它们,那么拥有特定的清理函数通常是不好的设计,因为您可能会忘记调用它们,否则可能会发生异常。考虑将它们放在你的析构函数中。
  • @Kiran 我很幸运你想立即开始使用 C++11,因为我可以从标签中得知。确保养成尽可能避免无人看管的指针的习惯,并改用std::unique_ptr and std::shared_ptr。那将是例如这里避免了实现自定义 dtor(“析构函数”的缩写)的必要性。
  • 您似乎认为向类添加成员的顺序以某种方式控制了代码运行的顺序?它没有。 main() 中调用成员函数的行决定了代码运行的顺序。

标签: c++ c++11 constructor destructor dynamic-memory-allocation


【解决方案1】:

您的析构函数已声明,但从未定义。

看起来像“post_destructor”做实际的破坏。因此,您需要做的就是编写如下的析构函数:

~Book() {}  // empty, nothing to do here...

【讨论】:

  • 在析构函数中肯定有一些事情要做。看看他的数据成员。他还有两个函数,称为pre_destructor()post_destructor()。他必须释放在他的构造函数中分配的内存。
  • 是的,但他已经在 post_destructor() 中“破坏”了。我同意这里有指针,但是如果他手动调用“post_destructor()”,它在实际的析构函数被调用之前就已经被删除了。
  • TBH,我不确定他为什么有 pre 和 post 析构函数,并且不只是在析构函数内部进行破坏......
  • 你是对的。 main()里的代码我没看。
【解决方案2】:

我已经缩短了一点。前者void pre_destructor() 毫无意义;最好放在 dtor(“析构函数”的缩写)本身, post_destructor() 甚至可能有害。

#include <iostream>

class Book
{
private:
    int *pages;
    int *price;

public:
    Book() : pages(new int(300)), price(new int(8)) {}  

    ~Book() {
        std::cout << "The pages:" << *pages << "\n";
        std::cout << "The price:" << *price << "\n";
        delete price;
        delete pages;
    } 
};

int main()
{
    {
        Book book1;
    } //destructor is called here

    return 0;
}  

live 在 Coliru 的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多