使用析构函数后,代码显示“引用Book ::〜Book()”错误

时间:2015-11-21 03:37:05

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

我是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

2 个答案:

答案 0 :(得分: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的

答案 1 :(得分:1)

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

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

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